onCreate的savedInstanceState和onRestoreInstanceState 方法的區別。

總結了下:


oncreate是在onstart之前執行是activity聲明週期,而onRestoreInstanceState 是在onstart之後onresume之前執行。

stackoverflow上看到的一個比較好的解釋:

onRestoreInstanceState is redundant because you can easily restore state in onCreate.
Having said that here is what the official doc says for onRestoreInstanceState:

Most implementations will simply use onCreate(Bundle) to restore their state, but it is sometimes convenient to do it here after all of the initialization has been done or to allow subclasses to decide whether to use your default implementation.

So for best practice, lay out your view hierarchy in onCreate and restore the previous state in onRestoreInstanceState. If you do that, anyone who subclasses your Activity can chose to override your onRestoreInstanceState to augment or replace your restore state logic. This is a long way of saying onRestoreInstanceState serves as a template method.

大致意思就是:

  onRestoreInstanceState 說白了很費官方說法就是爲了子類繼承方便調用。
 
 初始化操作在oncreate, 恢復數據在onRestoreInstanceState (參考上述生命週期,大致意思應該是oncreate應該執行一些初始化相關操作,在啓動和顯示之間操作一些)。
 只是爲了 子類繼承的時候業務邏輯分開。但是要把onRestoreInstanceState 說成是模板方法,也是漫漫長路。



發佈了39 篇原創文章 · 獲贊 30 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章