Activty嵌套多个Fragment,然后Fragment里面再嵌套多个Fragment,外层的Fragment切换得快了或者横竖屏切换就会报错:
java.lang.IllegalStateException: Activity has been destroyed
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1460)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:634)
at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:613)
怎么解决?
报错的是外层Fragment内的下面这段代码:
IndexListFragment indexHotFragment = new IndexListFragment();
Bundle bundle = new Bundle();
switch (id) {
case 1:
bundle.putSerializable("list", audit_handles);
bundle.putInt("id", 1);
break;
case 2:
bundle.putSerializable("list", pos_handles);
bundle.putInt("id", 2);
break;
case 3:
bundle.putSerializable("list", audit_lists);
bundle.putInt("id", 3);
break;
case 4:
bundle.putSerializable("list", pos_lists);
bundle.putInt("id", 4);
break;
default:
break;
}
indexHotFragment.setArguments(bundle);
FragmentManager fragmentManager = getChildFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(flContainer, indexHotFragment);
ft.commit();
然后我查了网上的资料,都说加下面一段:
@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);
}
}
这个方法怎么用,“mChildFragmentManager”需要替换成什么,,感觉不管用呢?
怪我咯2017-04-17 17:40:01
Actually, one way is
if(getActivity()==null){
return;
}
if(getActivity().isFishing()){
return;
}
I don’t know if you can understand what I mean.
大家讲道理2017-04-17 17:40:01
You need to restore the fragment saved for you in FragmentManager.
Before creating the fragment, check the savedInstanceState, like this:
@Override
public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
if (savedInstanceState != null) {
FragmentManager fm = getChildFragmentManager();
// tag 是你在add fragment的时候穿进去的值.
mFragment = (Fragment) fm.findFragmentByTag(tag);
}
}
In addition, I am curious about how you add the fragment when it is nested. Don't you also use reflection to get the mChildFragmentManager and then operate it? getChildFragmentManager()
You can get the childFragmentManager.
For details, please refer to https://segmentfault.com/q/10...