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

后端 未结 9 1566
终归单人心
终归单人心 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();
    

    0 讨论(0)
  • 2020-11-22 06:25

    Important thing to be noticed:

    Difference between Replace and Replace with backstack is whenever we use only replace then the fragment is destroyed ( ondestroy() is called ) and when we use replace with backstack then fragments onDestroy() is not called ( i.e when back button is pressed fragment is invoked with its onCreateView())

    0 讨论(0)
  • 2020-11-22 06:30

    The FragmentManger's function add and replace can be described as these 1. add means it will add the fragment in the fragment back stack and it will show at given frame you are providing like

    getFragmentManager.beginTransaction.add(R.id.contentframe,Fragment1.newInstance(),null)

    2.replace means that you are replacing the fragment with another fragment at the given frame

    getFragmentManager.beginTransaction.replace(R.id.contentframe,Fragment1.newInstance(),null)

    The Main utility between the two is that when you are back stacking the replace will refresh the fragment but add will not refresh previous fragment.

    0 讨论(0)
提交回复
热议问题