Got exception: fragment already active

前端 未结 8 1656
攒了一身酷
攒了一身酷 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:05

    Had the same issue. I was adding the fragment to backstack. And the error was because I didn't call popbackstack(). Using popbackstack helped me

    0 讨论(0)
  • 2021-01-30 13:07
    1. Check whether your layout current one or old one for example

      setContentView(R.layout.activity_main);
      
    2. Delete old .gradle file in your project file and rebuild gradle file for project.

    0 讨论(0)
  • 2021-01-30 13:16

    Try removing the previous fragment before adding the new one: https://stackoverflow.com/a/6266144/969325

    0 讨论(0)
  • 2021-01-30 13:21

    Reading the setArguments(Bundle args) source will help you understand:

    /**
    * Supply the construction arguments for this fragment.  This can only
    * be called before the fragment has been attached to its activity; that
    * is, you should call it immediately after constructing the fragment.  The
    * arguments supplied here will be retained across fragment destroy and
    * creation.
    */
    public void setArguments(Bundle args) {
    
        if (mIndex >= 0) {
            throw new IllegalStateException("Fragment already active");
        }
        mArguments = args;
    }
    

    You cannot use setArguments(Bundle args) again in your code on the same Fragment. What you want to do I guess is either create a new Fragment and set the arguments again. Or you can use getArguments() and then use the put method of the bundle to change its values.

    0 讨论(0)
  • 2021-01-30 13:21

    I'm running into the same issue on Xamarin.android. Here's what the documentation says.

    This can only be called before the fragment has been attached to its activity

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题