引言
首先,要明確什麼叫“非中斷保存”。熟悉Fragment的開發人員都知道,Fragment是依附於Activity的。當Activity銷燬時,Fragment會隨之銷燬。而當Activity配置發生改變(如屏幕旋轉)時候,舊的Activity會被銷燬,然後重新生成一個新屏幕旋轉狀態下的Activity,自然而然的Fragment也會隨之銷燬後重新生成,而新生成的Fragment中的各個對象也與之前的那個Fragment不一樣,伴隨着他們的動作、事件也都不一樣。所以,這時候如果想保持原來的Fragment中的一些對象,或者想保持他們的動作不被中斷的話,就迫切的需要將原來的Fragment進行非中斷式的保存。
生命週期
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;
}
}
來源: <https://github.com/android/platform_frameworks_base/blob/master/core/java/android/app/FragmentManager.java>
當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;
}
如果想叫自己的Fragment即使在其Activity重做時也不進行銷燬那麼就要設置setRetainInstance(true)。進行了這樣的操作後,一旦發生Activity重組現象,Fragment會跳過onDestroy直接進行onDetach(界面消失、對象還在),而Framgnet重組時候也會跳過onCreate,而onAttach和onActivityCreated還是會被調用。需要注意的是,要使用這種操作的Fragment不能加入backstack後退棧中。並且,被保存的Fragment實例不會保持太久,若長時間沒有容器承載它,也會被系統回收掉的。