0

我有一个带有 3 个片段的 ViewPager 和我的 FragmentPagerAdapter:

private class test_pager extends FragmentPagerAdapter {
    public test_pager(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int i) {
        return fragments[i];
    }

    @Override
    public long getItemId(int position) {
        if (position == 1) {
            long res = fragments[position].hashCode()+fragment1_state.hashCode();
            Log.d(TAG, "getItemId for position 1: "+res);
            return res;
        } else
            return fragments[position].hashCode();
    }

    @Override
    public int getCount() {
        return fragments[2] == null ? 2 : 3;
    }

    @Override
    public int getItemPosition(Object object) {
        Fragment fragment = (Fragment) object;
        for (int i=0; i<3; i++)
            if (fragment.equals(fragments[i])){
                if (i==1) {
                    return 1; // not sure if that makes a difference
                }
                return POSITION_UNCHANGED;
            }

        return POSITION_NONE;
    }
}

在其中一页(#1)中,我不断更改要显示的片段。我删除旧片段的方式是这样的:

FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction().remove(old_fragment1).commit();

然后只是改变价值fragments[1]

我发现我真的不能addreplace新的,否则它会抱怨 ViewPager 也试图用另一个标签添加它......(我在这里做错了吗?)

我展示的所有片段都有setRetainInstance(true);onCreate功能。

我的问题是这通常适用于前几次替换,但是当我尝试重用一个片段时,有时(我还没有真正弄清楚模式,在这种情况发生之前,同一个片段可能会显示多次)它只会显示空白页。

这是我在问题发生时尝试显示的片段的回调函数中发现的情况:

  • onAttach被调用(但当时getView还是null)
  • onCreateView不被调用(这是预期的)
  • onViewStateRestored不叫(为什么不呢?)
  • onResume不叫(我真的以为会...)

如果它改变了任何东西,我正在使用支持包,我的活动是SherlockFragmentActivity

编辑(回答马可的评论):

片段在 Activity 的 onCreate 函数中实例化,我用这些片段填充 ArrayList:

char_tests = new ArrayList<Fragment>(Arrays.asList(
            new FragmentOptionA(), new FragmentOptionB(), new FragmentOptionC()));

我从该列表中选择进行设置fragments[1](这一切都在 UI 线程中完成)

4

1 回答 1

0

I fixed this by changing test_pager to extends FragmentStatePagerAdapter instead.

I am still confused as to what PagerAdapter should be used depending on the usage. The only thing I can find in the documentation says that FragmentPagerAdapter is better for smaller number of pages that would be kept in memory and FragmentPagerStateAdapter better for a larger number of pages where they would be destroyed and save memory...

When trying to do (fancy?) things with Fragments, I found FragmentStatePagerAdapter is better when pages are removed and re-inserted like in this case. And FragmentPagerAdapter is better when pages move position (see bug 37990)

于 2012-11-28T03:13:07.920 回答