popBackStack causes calling oncreateView of fragment again and again

后端 未结 3 1792
孤城傲影
孤城傲影 2021-02-19 04:40

I have 3 fragment A, B,C.I wrote piece of code for replacing them and maintaining backstack:

 public void addFragment(Fragment fragmentToAdd, String fragmentTag)         


        
3条回答
  •  不知归路
    2021-02-19 05:06

    I solved this problem by inheriting (1) all fragments from my custom BaseFragment (2). In this BaseFragment I created a variable: public static boolean removing; (3) and set it to true (4) before calling popBackStackImmediate() and reset it to false after that. (5) In the BaseFragment-childs I check the variable. (6)

    Example-Code

    Activity-class

        BaseFragment.removing = true; //(4)
        //pop all fragments
        while(getSupportFragmentManager().getBackStackEntryCount() > 0){
            fragmentManager.popBackStackImmediate();
        }
        BaseFragment.removing = false; //(5)
    

    BaseFragment (2)

    public class BaseFragment extends Fragment{
       public static boolean removing = false; //(3)
    }
    

    Fragment-Child

    public class fragment extends BaseFragment{ //(1)
      @Override
      public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
          if(!removing){ // (6)
              //your code
          }
      }
    }
    

提交回复
热议问题