0

Suppose a FragmentActivity is supposed to have two different Fragments (side by side where the right one is twice the width of the left one), which will be added dynamically.

How do we tell the system which Fragment goes into which FrameLayout?

If it was a single Fragment in the Activity, I would simply override onCreateView() which would receive the container FrameLayout as a parameter, and I would return the inflated layout of the Fragment.

But now that I have two FrameLayouts and two Fragments to add in them, how would I tell the system which FrameLayout in the Activity I want to add my Fragment into?

Solace
  • 8,612
  • 22
  • 95
  • 183

2 Answers2

2

You could do two FragmentTransaction's like this in the onCreate(Bundle savedInstanceState) method of the FragmentActivity:

Transaction 1

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.framelayout1, new Fragment1());
ft.commit(); 

Transaction 2

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.framelayout2, new Fragment2());
ft.commit(); 
Steve
  • 836
  • 1
  • 9
  • 17
  • 1
    Even better is Shivams answer. But with `FragmentActivity` [Google docs](http://developer.android.com/reference/android/support/v4/app/FragmentActivity.html) states: `When using this class as opposed to new platform's built-in fragment and loader support, you must use the getSupportFragmentManager() and getSupportLoaderManager() methods respectively to access those features.` – Steve Jan 06 '15 at 08:07
  • I am following a code sample, and they did something like `fragmentTransaction.add(android.R.id.content, searchResultsListFragment);`, where the only explanation of `android.R.id.content` I could find was that "it gives the root element of a view without the need to know its name/type/id" [reference](http://stackoverflow.com/questions/7776768/android-what-is-android-r-id-content-used-for) - so I thought the first argument of `add()` had to be the root element in the `Fragment`'s layout. Let me try this one. – Solace Jan 06 '15 at 08:10
  • 1
    @Zarah from Google docs, the `add(int containerViewId, Fragment fragment)` first parameter (`containerViewId`) has the following description: `Optional identifier of the container this fragment is to be placed in. If 0, it will not be placed in a container.` [Google doc](http://developer.android.com/reference/android/app/FragmentTransaction.html#add) – Steve Jan 06 '15 at 08:17
  • 1
    Yep. You should use `getSupportFragmentManager()` and `getSupportLoaderManager()` methods – Shivam Verma Jan 06 '15 at 09:37
1

How about this ? :

SampleFragment1 fragment_1 = new SampleFragment1();
SampleFragment2 fragment_2 = new SampleFragment2();

FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.add(R.id.frameLayout1, fragment_1);
transaction.add(R.id.frameLayout2, fragment_2);
transaction.commit();
Shivam Verma
  • 7,973
  • 3
  • 26
  • 34