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

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

    When We Add First Fragment --> Second Fragment using add() method

     btn_one.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(getActivity(),"Click First 
    Fragment",Toast.LENGTH_LONG).show();
    
                    Fragment fragment = new SecondFragment();
                    getActivity().getSupportFragmentManager().beginTransaction()
                            .add(R.id.fragment_frame, fragment, fragment.getClass().getSimpleName()).addToBackStack(null).commit();
    //                        .replace(R.id.fragment_frame, fragment, fragment.getClass().getSimpleName()).addToBackStack(null).commit();
    
                }
            });
    

    When we use add() in fragment

    E/Keshav SecondFragment: onAttach
    E/Keshav SecondFragment: onCreate
    E/Keshav SecondFragment: onCreateView
    E/Keshav SecondFragment: onActivityCreated
    E/Keshav SecondFragment: onStart
    E/Keshav SecondFragment: onResume
    

    When we use replace() in fragment

    going to first fragment to second fragment in First -->Second using replace() method

     btn_one.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(getActivity(),"Click First Fragment",Toast.LENGTH_LONG).show();
    
                    Fragment fragment = new SecondFragment();
                    getActivity().getSupportFragmentManager().beginTransaction()
    //                        .add(R.id.fragment_frame, fragment, fragment.getClass().getSimpleName()).addToBackStack(null).commit();
                            .replace(R.id.fragment_frame, fragment, fragment.getClass().getSimpleName()).addToBackStack(null).commit();
    
                }
            });
    
    E/Keshav SecondFragment: onAttach
    E/Keshav SecondFragment: onCreate
    
    E/Keshav FirstFragment: onPause -------------------------- FirstFragment
    E/Keshav FirstFragment: onStop --------------------------- FirstFragment
    E/Keshav FirstFragment: onDestroyView -------------------- FirstFragment
    
    E/Keshav SecondFragment: onCreateView
    E/Keshav SecondFragment: onActivityCreated
    E/Keshav SecondFragment: onStart
    E/Keshav SecondFragment: onResume
    

    In case of Replace First Fragment these method is extra called ( onPause,onStop,onDestroyView is extra called )

    E/Keshav FirstFragment: onPause

    E/Keshav FirstFragment: onStop

    E/Keshav FirstFragment: onDestroyView

提交回复
热议问题