Got exception: fragment already active

前端 未结 8 1666
攒了一身酷
攒了一身酷 2021-01-30 12:49

I have a fragment;

MyFragment myFrag = new MyFragment();

I put bundle data to this fragment:

         


        
8条回答
  •  情歌与酒
    2021-01-30 13:25

    First I start with describing why this happens and then I'll come up with the solution I found working... .

    This issue happens when Android is removing the fragment from the stack but is not yet finished with removing. In order to check this, you can use the isRemoving() method of the fragment. If false, i.e. the fragment is not active, you can go on with setting the arguments using setArguments(bundle). Otherwise, you can't set arguments to an already active fragment and can only override it by addressing the same arguments using getArguments().putAll(bundle).

    To summarize,

        if (myFrag.isRemoving()) {
            myFrag.getArguments().putAll(bundle);
        } else {
            myFrag.setArguments(bundle);
        }
    

    If you want to avoid this, i.e. removing the fragment at once so there is no active fragment, you might want to use onBackPressed() in onBackStackChangedListener(), which will set the isRemoving() to false.

提交回复
热议问题