不调用onSaveInstanceState()和onRestoreInstanceState(Parcelable状态)?

Mar*_* S. 11 android android-custom-view android-view

我有一个扩展LinearLayout的自定义视图.我已经实现了onSaveInstanceState()和onRestoreInstanceState()来保存当前的视图状态.但是,不采取任何行动.当我在这两种方法中放置一个日志时,Log Cat中也没有任何内容.我认为这两种方法甚至都没有被调用.任何人都可以解释问题在哪里?谢谢.

@Override
public Parcelable onSaveInstanceState() {
    Bundle bundle = new Bundle();
    bundle.putParcelable("instanceState", super.onSaveInstanceState());
    bundle.putInt("currentPage", currentPage);
    return bundle;
}

@Override
public void onRestoreInstanceState(Parcelable state) {

    if (state instanceof Bundle) {
      Bundle bundle = (Bundle) state;
      currentPage = bundle.getInt("currentPage");
      Log.d("State", currentPage + "");
      super.onRestoreInstanceState(bundle.getParcelable("instanceState"));
      return;
    }
       super.onRestoreInstanceState(state);
  }
Run Code Online (Sandbox Code Playgroud)

Mar*_* S. 4

在深入了解 android 操作系统后,我终于弄清楚了。正如我所怀疑的:这两种方法没有任何问题。他们只是没有被召唤。在网络上,您可以读到“重新创建活动时调用 onRestoreInsatnceState”好吧,这很有道理,但并不完全正确。是的,重新创建 Activity 时会调用 onRestoreInstanceState(),但仅当且仅当:

它被操作系统杀死了。“这种情况发生在以下情况:

  • 设备的方向发生变化(您的 Activity 被销毁并重新创建)
  • 您前面有另一个活动,并且在某个时候操作系统会终止您的活动以释放内存(例如)。下次当您启动 Activity 时,将调用 onRestoreInstanceState()。”

因此,如果您在 Activity 中并点击设备上的“后退”按钮,您的 Activity 就会完成(),下次您启动应用程序时,它会再次启动(听起来像是重新创建的,不是吗?)但这一次没有保存状态,因为当您点击“后退”按钮时故意退出它。

  • 我遇到了完全相同的问题,但这是因为我的自定义“View”没有设置“id”。从文档中 _“请注意,即使启用了冻结,视图仍然必须有一个分配给它的 id(通过 setId(int))才能保存其状态。”_ (6认同)