2.生命周期
Activity的生命周期在配置发生改变时:
onPuase->onStop->onDestroy->onStart->onResume
比如在Activity中发生屏幕旋转,其生命周期就是如此。而在onDestroy中,Activity会将其FragmentManager所包含的Fragment都销毁掉(默认状态),即Fragment的生命周期为:
onDestroyView->onDestroy->onDetach
通过查看FragmentManager.java的代码,可以发现在Fragment生命周期执行到onDestroyView时候,状态会由正常的ACTIVITY_CREATED变为CREATED。而到了onDestroy生命周期时候,执行的代码出现了有意思的事情:
if (!f.mRetaining) {
f.performDestroy();
}
f.mCalled = false;
f.onDetach();
if (!f.mCalled) {
throw new SuperNotCalledException("Fragment " + f
+ " did not call through to super.onDetach()");
}
if (!keepActive) {
if (!f.mRetaining) {
makeInactive(f);
} else {
f.mActivity = null;
f.mParentFragment = null;
f.mFragmentManager = null;
}
}
当Fragment的mRetaining被置true的时候,Destroy生命周期并不会执行,而Fragment的mRetaining状态是通过其retainNonConfig()来配置的,配置条件是Fragment不为空且Framgnet的mRetainInstance为true。到这里就能看到,如果想要自己的Fragment不被销毁掉,就要让这个mRetainInstance为true。
通过查阅Fragment.java源码发现,通过API setRetainInstance和getRetainInstance可以对其进行操作。同样,Android文档中对这两个接口也有了一定的描述。
这里结合Fragment.java中setRetainInstance的注释进行一下Fragment非中断保存的总结。原注释如下:
/**
* Control whether a fragment instance is retained across Activity
* re-creation (such as from a configuration change). This can only
* be used with fragments not in the back stack. If set, the fragment
* lifecycle will be slightly different when an activity is recreated:
* <ul>
* <li> {@link #onDestroy()} will not be called (but {@link #onDetach()} still
* will be, because the fragment is being detached from its current activity).
* <li> {@link #onCreate(Bundle)} will not be called since the fragment
* is not being re-created.
* <li> {@link #onAttach(Activity)} and {@link #onActivityCreated(Bundle)} <b>will</b>
* still be called.
* </ul>
*/
public void setRetainInstance(boolean retain) {
if (retain && mParentFragment != null) {
throw new IllegalStateException(
"Can't retain fragements that are nested in other fragments");
}
mRetainInstance = retain;
}










