Highway62
Highway62

Reputation: 800

What happens to the current fragment once popBackStack() is called?

If I have a fragment loaded, fragment A, and replace that fragment with fragment B, adding fragment A to the backstack like so:

public void replaceFragment(Fragment frag, String fragTag) {
    mFragmentTransaction = mFragmentManager.beginTransaction();
    mFragmentTransaction.replace(R.id.fragmentContainer, frag, fragTag);
    mFragmentTransaction.addToBackStack(null);
    mFragmentTransaction.commit();
}

and then from fragment B I call:

popBackStackImmediate();

So that fragment A is loaded again. What happens to fragment B? In my code I am creating a new Fragment B object and loading it with my replaceFragment() method, and repeating the process. Am I creating a bunch of fragment B's every time I replace A with B and call popBackStack() or is B destroyed when popBackStack is called? Thanks.

Upvotes: 3

Views: 1661

Answers (1)

natario
natario

Reputation: 25194

popBackStack() reverses your last transaction, in your case, a replace transaction.

The FragmentTransaction docs are pretty clear about that. What replace does:

Replace an existing fragment that was added to a container. This is essentially the same as calling remove(Fragment) for all currently added fragments that were added with the same containerViewId and then add(int, Fragment, String) with the same arguments given here.

So, if A is added and you call replace(container, B), you are actually calling

  • remove(A)
  • add(B)

That said, reversing this transaction with popBackStack() essentially does:

  • remove(B)
  • add(A)

Which instance of A or B, you ask, it depends on how you use your method. As far as I know, a removed fragment will be destroyed (unless you keep a reference to it). If you call new Fragment() each time, than the answer is simple - you are creating lots of instances.

The FragmentTransaction API offers alternative ways to deal with situations like yours, in which you have to switch A and B more times. These are, again, well documented. For instance, you can use hide() and show() to hide fragment A and show fragment B, without having A garbage collected and creating unnecessary new instances.

In addition, you could use detach() and attach(). The difference with show and hide is that this way the fragment views (note: not the fragment instances) will be destroyed and recreated each time. Hide and show, on the other hand, just make the view invisible without destroying it.

Upvotes: 4

Related Questions