0

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?

1
  • It actually does replace. You must be doing something wrong but it is not apparent from the code you posted. Commented Apr 7, 2016 at 7:49

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.