1

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.

reubenjohn
  • 1,351
  • 1
  • 18
  • 43
  • 2
    `popBackStack()` only `pops/removes` the last `fragment` added on the `queue` and doesnt perform any further action. What dou you actually want to achieve? – hrskrs Jul 06 '15 at 15:49
  • @hrskrs You're right! It is just that that is what appears to be happening. I've changed my question to include a code snippet and a descriptive working. – reubenjohn Jul 06 '15 at 16:21

1 Answers1

0

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();
reubenjohn
  • 1,351
  • 1
  • 18
  • 43
  • With this solution, does the `fragmentA` show up when you press the back button? – Varun Jul 06 '15 at 18:10
  • No. However, a blank screen flashes right before FragmentC shows up. But I suppose it is not a related issue and can be fixed as shown [here](http://stackoverflow.com/q/23764477/2110869). – reubenjohn Jul 06 '15 at 18:45