FragmentStatePagerAdapter IllegalStateException异常:其中,MyFragment>是当前不在FragmentManager异常、IllegalSta

2023-09-05 07:06:21 作者:他霸占妳心中

我在某些情况下得到这一点,在onResume(),它采用了FragmentStatePagerAdapter的活动。使用设备的后退键时。不总是。不重复的。

I'm getting this on some cases, in onResume(), of an activity which uses a FragmentStatePagerAdapter. When using device's back button. Not always. Not reproducible.

我使用的是支持包V4,最后一次修改(8)。

I'm using support package v4, last revision (8).

已经搜索与谷歌,没有成功找到一个有用的答案。

Already searched with google, no success finding a useful answer.

寻找源代码中,都能在这里找到抛出:FragmentManager.java

Looking in the source, it's thrown here: FragmentManager.java

@Override
public void putFragment(Bundle bundle, String key, Fragment fragment) {
    if (fragment.mIndex < 0) {
        throw new IllegalStateException("Fragment " + fragment
                + " is not currently in the FragmentManager");
    }
    bundle.putInt(key, fragment.mIndex);
}

但是,为什么是片段LT的指标; 0呢?

But why is the index of fragment < 0 there?

在code实例片段:

@Override
public Fragment getItem(int position) {
    Fragment fragment = null;

    switch(position) {
        case 0:
            fragment = MyFragment.newInstance(param1);
            break;
        case 1:
            fragment = MyFragment2.newInstance(param2, param3);
            break;
    }
    return fragment;
}

@Override
public int getCount() {
    return 2;
}

我也无法通过源代码调试,因为支持包不让我重视的来源,因为某些原因...但是这是一个不同的问题...

I also can't debug through the source since the support package doesn't let me attach the source, for some reason... but that's a different question...

推荐答案

明白了,原因是,那我每次intantiating适配器在onResume()。

Got it, the reason was, that I'm intantiating the Adapter each time in onResume().

如果我实例适配器只有一次,在活动的生命周期,这不会发生了。

If I instantiate the adapter only once, in the life cycle of the activity, this does not happen anymore.