Search code examples
androidandroid-fragmentsandroid-fragmentactivityback-stackfragmenttransaction

If I add a new transaction(adding fragment, no removing) to the fragment backstack, do the fragment objects in previous transaction get copied or used


So let's say for my first transaction I add Fragment A, add to backstack, and commit.

For my second transaction, I add Fragment B, add to backstack, and commit.

At this point after my second transaction, I have both Fragment A and Fragment B existing. Is Fragment A still referring to the same Fragment A object I created in the first transaction or a copy of it?

I read somewhere saying that after each transaction, a snapshot of the fragments gets created and it only makes sense to me if existing fragments get copied so old snapshots don't get messed up by new ones.

How does it work exactly?


Solution

  • A FragmentTransaction that uses addToBackStack records just the minimum information around the operation - in your case, the Fragment that is added and the fact that it was an 'add' operation. The FragmentManager absolutely does not do any snapshot type of behavior.

    This is used in two ways:

    1. To execute the FragmentTransaction. An 'add' operation does not affect other Fragments (so Fragment A is not changed when you add Fragment B).
    2. When you pop the back stack (i.e., hit the system back button), the operation is reversed - an 'add' operation becomes a 'remove' operation. For a 'remove' operation, no other Fragment is changed (so Fragment A still exists when you pop Fragment B)

    Of course, other operations, such as 'replace' affect two Fragments (you can think of it as a 'remove' of the old Fragment and an 'add' of the new Fragment).