问题: mChildFrgamentManager
正在重新创建(https://code.google.com/p/android/issues/detail?id=74222)
解决方法:mChildFrgamentManager
如果片段有,则保留setRetainInstance(true)
:
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (getRetainInstance()) {
if (mRetainedChildFragmentManager != null) {
try {
Field childFMField = Fragment.class.getDeclaredField("mChildFragmentManager");
childFMField.setAccessible(true);
childFMField.set(this, mRetainedChildFragmentManager);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} else {
mRetainedChildFragmentManager = getChildFragmentManager();
}
}
}
警告:使用此代码,setRetainInstace
应在之前调用onAttach
。
PS:这是@attels 答案的一些改进版本。