Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace the top fragment on the back stack

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.

like image 362
ains Avatar asked Jul 06 '13 02:07

ains


People also ask

How to replace fragment?

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();

What is fragment back stack in android?

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.


1 Answers

Did you try to pop the back stack before you add fragment D:

FragmentManager fragmentManager = getFragmentManager();
fragmentManager.popBackStack(); // or popBackStackImmediate();
ft.addToBackStack(<fragmentD>);
like image 121
ilomambo Avatar answered Sep 30 '22 18:09

ilomambo