onSaveInstanceState () and onRestoreInstanceState ()

前端 未结 13 2344
孤城傲影
孤城傲影 2020-11-22 04:48

I\'m trying to save and restore the state of an Activity using the methods onSaveInstanceState() and onRestoreInstanceState().

13条回答
  •  余生分开走
    2020-11-22 05:32

    Usually you restore your state in onCreate(). It is possible to restore it in onRestoreInstanceState() as well, but not very common. (onRestoreInstanceState() is called after onStart(), whereas onCreate() is called before onStart().

    Use the put methods to store values in onSaveInstanceState():

    protected void onSaveInstanceState(Bundle icicle) {
      super.onSaveInstanceState(icicle);
      icicle.putLong("param", value);
    }
    

    And restore the values in onCreate():

    public void onCreate(Bundle icicle) {
      if (icicle != null){
        value = icicle.getLong("param");
      }
    }
    

提交回复
热议问题