关于getFragmentManager() 和 getChildFragmentManager() 两个方法

菜鸟第一次写博客,就拿在项目中遇到的问题来开篇吧

首先问题出现

一个activity里包含了一个fragment页面,一个fragment里有多个fragment,采用的技术是viewpager + fragment,第一次进入fragment加载都没问题,生命周期也都执行了。由于我的项目里该activity的launchMode是singleTask模式,当第二次进入该activity时,viewpager里的fragment加载就出问题了,生命周期都没执行。

问题解决

后来发现是getFragmentManager()和getChildFragmentManager() 两个方法的错误使用导致。

看下源码

/**
 * Return the FragmentManager for interacting with fragments associated
 * with this fragment's activity.  Note that this will be non-null slightly
 * before {@link #getActivity()}, during the time from when the fragment is
 * placed in a {@link FragmentTransaction} until it is committed and
 * attached to its activity.
 *
 * 

If this Fragment is a child of another Fragment, the FragmentManager * returned here will be the parent's {@link #getChildFragmentManager()}. */ final public FragmentManager getFragmentManager() { return mFragmentManager; } /** * 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; }

 源码注释讲的很清楚getFragmentManager()获取到的管理器是针对fragment所依附的activity来讲,也就是在activity里管理一级子fragment所使用的,如果fragment里面还有fragment,就应该使用getChildFragmentManager() 方法,修改后确实问题解决了。

你可能感兴趣的:(android)