Jan
Jan

Reputation: 3401

Backstack order on replacing fragments

Say I have 4 fragments.

Fragment A is created at first. In fragment A, I have a method that replaces fragment A to other 4 fragments. Of course, addToBackStack() is included. This method is also present in other fragments.

Now I use that method to replace Fragment A to Fragment B. Fragment A is now in the backstack.

Order is oldest to newest

Stack now is : A B

Then in fragment B, i replace it with fragment C.

Stack now is: A B C

Then I replace fragment C with D.

Stack now is: A B C D

Correct me if I'm wrong here

Questions:

  1. If I replace Fragment D with Fragment A, what happens to B and C. Do they pop off the stack? What now is the correct order.

  2. If I replace Fragment D with Fragment A, does android create another A or reuse the previous A to make a new one? So the stack now is A B C D A?

Upvotes: 1

Views: 490

Answers (3)

Gopal Singh Sirvi
Gopal Singh Sirvi

Reputation: 4649

Better way to replacing fragments is to add the transactions to the backstack with a tag and whenever you want any previous fragment then pop the backstack with that tag which was earlier added to that transaction.

getFragmentManager().beginTransaction().replace(R.id.container,new MyFragment()).addToBackStack("mytag").commit();

And for popping back

getFragmentManager().popBackStack("mytag");

With this approach if you pop the backstack for fragment A then the stack will popped means upper fragments of A is also removed

Upvotes: 0

DDsix
DDsix

Reputation: 1984

Well, if you replace fragment D with a new instance of fragment A, like FragmentA.newInstance(), the backstack will now be A B C D A. If, however, you don't want this behaviour, you can retrieve fragment A from the backstack and use that instance instead.

Upvotes: 0

user1136881
user1136881

Reputation: 172

If you replace Fragment D with Fragment A, android creates another A, so the stack now is A B C D A.

Upvotes: 1

Related Questions