Sergei Ledvanov
Sergei Ledvanov

Reputation: 2251

Why does not `replace` replace a fragment?

I have the following code that adds fragments to the same container R.id.container. First I add one fragment, then after user interacts with it, I add another one with the same code

FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.container, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();

My question when I cell getSupportFragmentManager().getFragments() I can see two fragments. Why doesn't replace actually replace but add?

Upvotes: 0

Views: 116

Answers (1)

NitroG42
NitroG42

Reputation: 5356

It keeps the two fragments because

addToBackStack(null);

means the user is able to revert back to the previous state. If you add fragment1 (using replace), then fragment2, only fragment2 is shown, but if the user press back, the FragmentManager needs to show fragment1, so it keeps a reference to both fragment.

Upvotes: 1

Related Questions