Difference between add(), replace(), and addToBackStack()

后端 未结 9 1585
终归单人心
终归单人心 2020-11-22 05:40

What is the main difference between calling these methods:

fragmentTransaction.addToBackStack(name);
fragmentTransaction.replace(containerViewId, fragment, t         


        
9条回答
  •  一生所求
    2020-11-22 06:25

    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();
    

提交回复
热议问题