Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swapping Fragments in a Single Activity?

On the tablet we have two fragments (two different views of the same data) that sit next to each other. On mobile devices we'd like to switch between these two fragments at the push of a button. The mobile layout looks something like this:

<RelativeLayout>
  <fragment id="container" name="fragA"/>
  <ImageButton onClick="swapFragments" />
</RelativeLayout>

In the activity's swapFragments(View) method, I'm attempting to use the FragmentManager to replace fragA with fragB:

FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container, new FragB());
fragmentTransaction.commit();

...but I can always see fragA through the transparent parts of fragB, leading me to believe that it's just putting fragB on top of fragA, not replacing it.

I'm starting down the path of using hide(Fragment) and similar methods in the transaction, but that doesn't look like the right way to do it.

Any tips on how to swap these fragments the right way?

Edit: I saw the answer to this question. This confuses me, though, as I need to be able to specify a different layout for tablet and phone. If I have to programmatically add fragments, how do I avoid code specific to each layout in the activity (i.e.

 if(TABLET) {
   addFragmentA();
   addFragmentB();
 } else {
   addFragmentA();
 }
like image 520
magneticMonster Avatar asked Jun 15 '11 16:06

magneticMonster


1 Answers

Don't mix Fragments created in XML and in Code - bad things will happen. Keep a container view in the layout, then add / replace fragments into it (don't have the first fragment inside it).

like image 103
FunkTheMonk Avatar answered Sep 16 '22 13:09

FunkTheMonk