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

后端 未结 9 1569
终归单人心
终归单人心 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:10

    Example an activity have 2 fragments and we use FragmentManager to replace/add with addToBackstack each fragment to a layout in activity

    Use replace

    Go Fragment1

    Fragment1: onAttach
    Fragment1: onCreate
    Fragment1: onCreateView
    Fragment1: onActivityCreated
    Fragment1: onStart
    Fragment1: onResume
    

    Go Fragment2

    Fragment2: onAttach
    Fragment2: onCreate
    Fragment1: onPause
    Fragment1: onStop
    Fragment1: onDestroyView
    Fragment2: onCreateView
    Fragment2: onActivityCreated
    Fragment2: onStart
    Fragment2: onResume
    

    Pop Fragment2

    Fragment2: onPause
    Fragment2: onStop
    Fragment2: onDestroyView
    Fragment2: onDestroy
    Fragment2: onDetach
    Fragment1: onCreateView
    Fragment1: onStart
    Fragment1: onResume
    

    Pop Fragment1

    Fragment1: onPause
    Fragment1: onStop
    Fragment1: onDestroyView
    Fragment1: onDestroy
    Fragment1: onDetach
    

    Use add

    Go Fragment1

    Fragment1: onAttach
    Fragment1: onCreate
    Fragment1: onCreateView
    Fragment1: onActivityCreated
    Fragment1: onStart
    Fragment1: onResume
    

    Go Fragment2

    Fragment2: onAttach
    Fragment2: onCreate
    Fragment2: onCreateView
    Fragment2: onActivityCreated
    Fragment2: onStart
    Fragment2: onResume
    

    Pop Fragment2

    Fragment2: onPause
    Fragment2: onStop
    Fragment2: onDestroyView
    Fragment2: onDestroy
    Fragment2: onDetach
    

    Pop Fragment1

    Fragment1: onPause
    Fragment1: onStop
    Fragment1: onDestroyView
    Fragment1: onDestroy
    Fragment1: onDetach
    

    Sample project

提交回复
热议问题