Search code examples
androidandroid-fragmentsfragment-backstackfragmentmanager

How to replace only the item at the top of a fragment back stack with another fragment?


When I perform getSupportFragmentManager().popBackStack(); it pops the back stack and performs the fragment transaction associated with the popped back stack entry.

I have 3 fragment:
- FragmentA
- FragmentB
- FragmentC

My activity performs 3 transactions when promoted by the user:

  1. Fragment A is first added to my container.
  2. Then FragmentA is detached and FragmentB is added. And the transaction is added to the back stack.
  3. Then what I want is for FragmentC to replace only fragmentB and change the back stack entry such that when the user presses the back button, FragmentA should show up.

Here is my code that performs transaction 3:

FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
fm.popBackStack();
ft.remove(fragmentB)
    .add(R.id.container, fragmentC, tag)
    .addToBackStack(null)
    .commit();

Transactions 1 and 2 seem to work fine. However, when I attempt to perform transaction 3, what happens is that FragmentB is replaced by FragmentC but Fragment A also shows up right before FragmentC is drawn over it and FragmentA continues to be seen behind FragmentC.

What am I doing wrong? How can I replace FragmentB with FragmentC without having FragmentA reveal in the background.


Solution

  • I found a workaround if not a solution.

    It seems that in transaction 3, when I remove FragmentB the previously detached FragmentA automatically gets added. That was what was causing FragmentA to be shown behind FragmentC.

    The workaround is to detach FragmentA again after removing FragmentA like so:

    ft.remove(fragmentB)
        .detach(fragmentA) // Detach FragmentA that is automatically added by the removing of fragmentB
        .add(R.id.container, fragmentC, tag)
        .addToBackStack(null)
        .commit();