commitAllowingStateLoss() and commit() fragment

前端 未结 5 981
陌清茗
陌清茗 2021-02-04 03:47

I want commit a fragment after network background operation. I was calling commit() after successful network operation but in case activity goes to pause or stop state it was cr

5条回答
  •  南笙
    南笙 (楼主)
    2021-02-04 04:12

    Simple way would be waiting for Activity to resume, so you can commit your action, a simple workaround would look something like this:

    @Override
    public void onNetworkResponse(){
           //Move to next fragmnt if Activity is Started or Resumed
           shouldMove = true;
           if (isResumed()){
                moveToNext = false;
    
                //Move to Next Page
                getActivity().getSupportFragmentManager()
                        .beginTransaction()
                        .replace(R.id.fragment_container, new NextFragment())
                        .addToBackStack(null)
                        .commit();
           }
    }
    

    So if Fragment is resumed (Hence Activity) you can commit your action but if not you will wait for Activity to start to commit your action:

    @Override
    public void onResume() {
        super.onResume();
    
        if(moveToNext){
            moveToNext = false;
    
            //Move to Next Page
            getActivity().getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.fragment_container, new NextFragment())
                    .addToBackStack(null)
                    .commit();
        }
    }
    

    P.S: Pay attention to moveToNext = false; It is there to ensure that after commit you won't repeat commit in case of coming back using back press..

提交回复
热议问题