fragment嵌套fragment不显示问题(viewpager)

小伙伴们有没有遇到过这个问题呢?
不多废话,上我的解决办法:
我们在new PagerAdapter的时候如果是用

MyPagerAdapter mAdapter = new MyPagerAdapter(mycontext.getSupportFragmentManager(), mFragmentList, mycontext);

或者是:

 MyPagerAdapter mAdapter = new MyPagerAdapter(mycontext.getFragmentManager(), mFragmentList, mycontext);

改成这种样式可以正常显示了:

 MyPagerAdapter mAdapter = new MyPagerAdapter(getChildFragmentManager(), mFragmentList, mycontext);

核心:把getFragmentManager(),getSupportFragmentManager()换成getChildFragmentManager()。

下面提供一下后者的源码:

    /**
     * Return a private FragmentManager for placing and managing Fragments
     * inside of this Fragment.
     */
    final public FragmentManager getChildFragmentManager() {
        if (mChildFragmentManager == null) {
            instantiateChildFragmentManager();
            if (mState >= RESUMED) {
                mChildFragmentManager.dispatchResume();
            } else if (mState >= STARTED) {
                mChildFragmentManager.dispatchStart();
            } else if (mState >= ACTIVITY_CREATED) {
                mChildFragmentManager.dispatchActivityCreated();
            } else if (mState >= CREATED) {
                mChildFragmentManager.dispatchCreate();
            }
        }
        return mChildFragmentManager;
    }

原来这个方法的核心是判断当前的状态和fragment的生命周期对比,然后做事件分发,一定程度上就是像Activity 的Bundle savedInstanceState记录当前状态,后台静默保存,然后分发事件再次执行fragment的生命周期方法,防止被销毁掉。

你可能感兴趣的:(Android)