viewpager嵌套多层fragment出现的问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiaoshuxgh/article/details/83538847

最近新实现的功能是:一个Activity有四个按钮,实现切换,使用viewpager嵌套fragment,然后其中两个fragment要实现嵌套fragment,而且要求有滑动,效果图如下:

遇到的问题:商城跟咨询页面信息错乱,咨询不显示数据

之前界面只有咨询,没有商城页面时,数据显示正常,新加商城页面,咨询数据不显示,

因为之前数据显示正常,新增一个商城页面,也是fragment嵌套fragment,后边就确定

问题就在 new ViewPageAdpater( getFragmentManager() ); 这里。

之前就知道 fragment中嵌套fragment 应该使用 getChildFragmentManager() ,每次用起来都是忘了

如果你仔细查看Fragment的实现,你会看到当fragment进行到detached状态时,它会重置它的内部状态。

然而,它没有重置mChildFragmentManager.这是当前版本support库的一个bug.

这导致在Fragment重新attach时,它(fragment)没有重新attachm childFragmentManager,从而引发了上面的异常.

解决方法:

在每个调用getChildFragmentManager()的fragment中加入:

@Override
public void onDetach() {

    super.onDetach();

    try {

        Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");

        childFragmentManager.setAccessible(true);

        childFragmentManager.set(this, null);

    } catch (NoSuchFieldException e) {

        throw new RuntimeException(e);

    } catch (IllegalAccessException e) {

        throw new RuntimeException(e);

    }

}

使用:

mAdapterPager = new FragmentPagerItemAdapter(getChildFragmentManager(), mPagesFragment);

完美解决!

猜你喜欢

转载自blog.csdn.net/xiaoshuxgh/article/details/83538847
今日推荐