Android應用開發:Fragment的非中斷保存setRetaineInstance

引言

首先,要明確什麼叫“非中斷保存”。熟悉Fragment的開發人員都知道,Fragment是依附於Activity的。當Activity銷燬時,Fragment會隨之銷燬。而當Activity配置發生改變(如屏幕旋轉)時候,舊的Activity會被銷燬,然後重新生成一個新屏幕旋轉狀態下的Activity,自然而然的Fragment也會隨之銷燬後重新生成,而新生成的Fragment中的各個對象也與之前的那個Fragment不一樣,伴隨着他們的動作、事件也都不一樣。所以,這時候如果想保持原來的Fragment中的一些對象,或者想保持他們的動作不被中斷的話,就迫切的需要將原來的Fragment進行非中斷式的保存。

生命週期

Activity的生命週期在配置發生改變時:

  1. onPuase->onStop->onDestroy->onStart->onResume

比如在Activity中發生屏幕旋轉,其生命週期就是如此。而在onDestroy中,Activity會將其FragmentManager所包含的Fragment都銷燬掉(默認狀態),即Fragment的生命週期爲:

  1. onDestroyView->onDestroy->onDetach

通過查看FragmentManager.java的代碼,可以發現在Fragment生命週期執行到onDestroyView時候,狀態會由正常的ACTIVITY_CREATED變爲CREATED。而到了onDestroy生命週期時候,執行的代碼出現了有意思的事情:

  1. if (!f.mRetaining) {
  2. f.performDestroy();
  3. }
  4. f.mCalled = false;
  5. f.onDetach();
  6. if (!f.mCalled) {
  7. throw new SuperNotCalledException("Fragment " + f
  8. + " did not call through to super.onDetach()");
  9. }
  10. if (!keepActive) {
  11. if (!f.mRetaining) {
  12. makeInactive(f);
  13. } else {
  14. f.mActivity = null;
  15. f.mParentFragment = null;
  16. f.mFragmentManager = null;
  17. }
  18. }
  19. 來源: <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非中斷保存的總結。原註釋如下:

  1. /**
  2. * Control whether a fragment instance is retained across Activity
  3. * re-creation (such as from a configuration change). This can only
  4. * be used with fragments not in the back stack. If set, the fragment
  5. * lifecycle will be slightly different when an activity is recreated:
  6. * <ul>
  7. * <li> {@link #onDestroy()} will not be called (but {@link #onDetach()} still
  8. * will be, because the fragment is being detached from its current activity).
  9. * <li> {@link #onCreate(Bundle)} will not be called since the fragment
  10. * is not being re-created.
  11. * <li> {@link #onAttach(Activity)} and {@link #onActivityCreated(Bundle)} <b>will</b>
  12. * still be called.
  13. * </ul>
  14. */
  15. public void setRetainInstance(boolean retain) {
  16. if (retain && mParentFragment != null) {
  17. throw new IllegalStateException(
  18. "Can't retain fragements that are nested in other fragments");
  19. }
  20. mRetainInstance = retain;
  21. }

如果想叫自己的Fragment即使在其Activity重做時也不進行銷燬那麼就要設置setRetainInstance(true)。進行了這樣的操作後,一旦發生Activity重組現象,Fragment會跳過onDestroy直接進行onDetach(界面消失、對象還在),而Framgnet重組時候也會跳過onCreate,而onAttach和onActivityCreated還是會被調用。需要注意的是,要使用這種操作的Fragment不能加入backstack後退棧中。並且,被保存的Fragment實例不會保持太久,若長時間沒有容器承載它,也會被系統回收掉的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章