[android] How to start Fragment from an Activity

I already want to start my RecipientFragment from my MainActivity and pass data onto the Fragment from my MainActivity. Here is the code that I have implemented. But the fragment does not start.

Bundle bundle = new Bundle();
bundle.putString(ParseConstants.KEY_FILE_TYPE, fileType);
RecipientsFragment keyfile = new RecipientsFragment();
keyfile.setArguments(bundle);
Fragment newFragment = new RecipientsFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.commit();

I also want to know how to pass intent.setData and get that data in Fragment. Currently I have below code:

RecipientFragment

mMediaUri = getActivity().getIntent().getData();

MainActivity

Intent recipientsIntent = new Intent(this, RecipientsFragment.class);
        recipientsIntent.setData(mMediaUri);

This question is related to android android-fragments

The answer is


You can either add or replace fragment in your activity. Create a FrameLayout in activity layout xml file.

Then do this in your activity to add fragment:

FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.container,YOUR_FRAGMENT_NAME,YOUR_FRAGMENT_STRING_TAG);
transaction.addToBackStack(null);
transaction.commit();

And to replace fragment do this:

FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.container,YOUR_FRAGMENT_NAME,YOUR_FRAGMENT_STRING_TAG);
transaction.addToBackStack(null);
transaction.commit();

See Android documentation on adding a fragment to an activity or following related questions on SO:

Difference between add(), replace(), and addToBackStack()

Basic difference between add() and replace() method of Fragment

Difference between add() & replace() with Fragment's lifecycle


Similar questions with android tag:

Similar questions with android-fragments tag: