Mohammad Karimi
Mohammad Karimi

Reputation: 87

how to add two fragments in one activity

Android: I have a list Fragment on an activity.based on the choice, another fragment will be shown on the same activity but the other fragment should be replaced and i don't know how to do that when the list fragment is fixed !

Upvotes: 1

Views: 2329

Answers (2)

stan0
stan0

Reputation: 11807

There's a guide on Fragments in the developers portal. Take a look at the "programmatically add" part (and at the whole guide actually). In short: you need a ViewGroup that is used as a container for the fragments and a FragmentTransaction that is used to add/replace fragment in this container.

Something like (taken from the guide):

FragmentManager fragmentManager = getFragmentManager()
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
ExampleFragment fragment = new ExampleFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);//fragment_container is the ID of the ViewGroup container in your layout
fragmentTransaction.commit();

in your activity.

EDIT:

Long story short - don't put a fixed fragment in your activity's layout. Instead place a container, dynamically add your first fragment in the container and replace it with another fragment when you need to do so (by using FragmentTransaction's replace).

Upvotes: 1

jithinroy
jithinroy

Reputation: 1885

From google guide for replacing fragments : http://developer.android.com/training/basics/fragments/fragment-ui.html

// Create fragment and give it an argument specifying the article it should show
ArticleFragment newFragment = new ArticleFragment();
Bundle args = new Bundle();
args.putInt(ArticleFragment.ARG_POSITION, position);
newFragment.setArguments(args);

FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit();

Upvotes: 1

Related Questions