I'm having so much trouble with Android fragments... Suppose my back stack looks like this
[C]
[B]
[A]
---
Pressing the back button would pop Fragment C
off, and leaving Fragment B
on the top of the stack. Now, how do I swap Fragment C
for Fragment D
while maintaining the back stack? Note, Fragment B
cannot be seen during the operation.
[C] <- [D] [D]
[B] -----> [B]
[A] [A]
--- ---
This way, pressing the back button would pop Fragment D
off, and leaving Fragment B
on top. Fragment C
is completely removed off the stack.
I add each fragments to the stack like so
FragmentTransaction ft = manager.beginTransaction();
ft.replace(id, instance, getTag(instance));
ft.addToBackStack(getTag(instance));
ft.commit();
I thought this could be achieved by doing the same calls without addToBackStack
, but it just made Fragment D
and Fragment B
overlapped.
Use replace() to replace an existing fragment in a container with an instance of a new fragment class that you provide. Calling replace() is equivalent to calling remove() with a fragment in a container and adding a new fragment to that same container. transaction. commit();
Calling addToBackStack() commits the transaction to the back stack. The user can later reverse the transaction and bring back the previous fragment by pressing the Back button. If you added or removed multiple fragments within a single transaction, all of those operations are undone when the back stack is popped.
Did you try to pop the back stack before you add fragment D:
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.popBackStack(); // or popBackStackImmediate();
ft.addToBackStack(<fragmentD>);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With