What is the main difference between calling these methods:
fragmentTransaction.addToBackStack(name);
fragmentTransaction.replace(containerViewId, fragment, t
Here is a picture that shows the difference between add()
and replace()
So add()
method keeps on adding fragments on top of the previous fragment in FragmentContainer.
While replace()
methods clears all the previous Fragment from Containers and then add it in FragmentContainer.
What is addToBackStack
addtoBackStack
method can be used with add() and replace methods. It serves a different purpose in Fragment API.
What is the purpose?
Fragment API unlike Activity API does not come with Back Button navigation by default. If you want to go back to the previous Fragment then the we use addToBackStack() method in Fragment. Let's understand both
Case 1:
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragmentContainer, fragment, "TAG")
.addToBackStack("TAG")
.commit();
Case 2:
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragmentContainer, fragment, "TAG")
.commit();