前言
项目中在使用Fragment中嵌套Fragment时,你可能会遇到这么一个问题,多次显示隐藏父Fragment之后子Fragment不显示。具体的表现是在父Fragment A中嵌套添加了一个子Fragment B。外部调用父Fragment A第一次显示时,FragmentA、B都正常显示;外部第二次调用父Fragment显示时,Fragment A正常显示,Fragment B显示空白。
问题回放
FragmentManager fm = getActivity().getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.fl_base_info,new FragmentA());
ft.commit();
问题:
- Fragment放ViewPager,ViewPager里面是fragment。第一次进入没问题,再次进入ViewPager的fragment时里面内容就没了,数据丢失。
- Fragment低频率点击切换不会发生问题,过快点击马上崩溃
- 错误:Java.lang.IllegalArgumentException:No view found for id for fragment
- 调用fragment的replace方法不走onDestroy()、onDestroyView()方法,无法销毁fragment
- 在fragment中写倒计时,每次切换后倒计时越来越快的问题
getSupportFragmentManager()主要用于支持 3.0以下android系统API版本,3.0以上系统可以直接调用getFragmentManager() ,因为fragment是3.0以后才出现的组件,为了这之前的系统版本也能使用fragment,借助V4包里面的getSupportFragmentManager()方法来间接获取FragmentManager()对象,3.0版本之后,有了Fragment的api,就可以直接使用getFragmentManager()这个方法来获取对象。
解决办法
FragmentManager fm = getChildFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.fl_base_info,new FragmentA());
ft.commit();
getFragmentManager到的是activity对所包含fragment的Manager,而如果是fragment嵌套fragment,那么就需要利用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.
*
* <p>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;
}
网友评论