java.lang.IllegalStateException:键f1的片段不再存在:索引3 [英] java.lang.IllegalStateException: Fragment no longer exists for key f1: index 3

查看:207
本文介绍了java.lang.IllegalStateException:键f1的片段不再存在:索引3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解此异常,以便实施适当的修复程序.

I want to understand this exception in order to implement a proper fix.

有一个ViewPager,它使用FragmentStatePagerAdapter通过getItem和MyFragmentClass.newInstance(...)实例化2个片段.

There's a ViewPager and it uses a FragmentStatePagerAdapter to instantiate 2 fragments via getItem and MyFragmentClass.newInstance(...).

适配器的getItem看起来像这样:

Adapter's getItem looks like this:

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

    switch(position) {
        case 0:
            fragment = MyFragment2.newInstance(par1);
            break;
        case 1:
            fragment = MyFragment2.newInstance(par2, par3);
            break;
    }
    return fragment;
}

问题:

当活动被销毁并再次创建时,适配器再次被实例化,使用MyFragmentClass.newInstance(...) ...再次创建了片段,但是在这一行:

When the activity is destroyed, and created again, the adapter is intantiated again, the fragments created again with MyFragmentClass.newInstance(...)... but then on this line:

pager.setAdapter(adapter);

我得到了提到的异常.

我查看了引发异常的源代码,就是这样:

I looked in the source where the exception is thrown, it's this:

@Override
public Fragment getFragment(Bundle bundle, String key) {
    int index = bundle.getInt(key, -1);
    if (index == -1) {
        return null;
    }
    if (index >= mActive.size()) {
        throw new IllegalStateException("Fragement no longer exists for key "
                + key + ": index " + index);
    }
    Fragment f = mActive.get(index);
    if (f == null) {
        throw new IllegalStateException("Fragement no longer exists for key "
                + key + ": index " + index);
    }
    return f;
}

因此,一个捆绑包被传递到那里,带有一些引用我的旧片段的状态,但这与当前状态(mActive)不对应,并且引发了异常.

So a bundle is passed there, with some state which references my old fragments, but this doesn't correspond to the current state (mActive), and the exception is thrown.

我不明白这背后的想法是什么,或者我应该以哪种方式实例化片段.

I don't understand what's the idea behind this, or which way I'm supposed to instantiate the fragments.

我尝试了从另一个上下文中获得的技巧:

I tried a trick I got from another context:

pager.setOffscreenPageLimit(1);

为了避免片段在屏幕外时被破坏(在使用2页viewpager的情况下,尽管不知道状态适配器是否可以很好地工作).但是似乎没有相关性,至少,它没有帮助,仍然会得到相同的异常.

In order to avoid that the fragments are destroyed when they are off screen (in the case of 2 pages viewpager, although don't know if it works well with state adapter). But don't seems to be related, at least, it doesn't help, still get the same exception.

捕获异常导致页面空白.

Catching the exception leads to the pages being blank.

推荐答案

这可能有帮助-

@Override
public Parcelable saveState() {
    return null;
}

FragmentStatePagerAdapter中的上方添加行.

这篇关于java.lang.IllegalStateException:键f1的片段不再存在:索引3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆