我有一个扩展 LinearLayout 的自定义 View 。我已经实现了 onSaveInstanceState() 和 onRestoreInstanceState() 来保存当前 View 状态。但是没有采取任何行动。当我在这两种方法中放置一个日志时,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);
}
最佳答案
在深入研究 android 操作系统之后,我终于弄明白了。正如我所怀疑的那样:这两种方法没有任何问题。他们只是没有被调用。 在 Web 上,您可以读到“重新创建 Activity 时调用 onRestoreInsatnceState” 好吧,这很有道理,但并不完全正确。是的,在重新创建 Activity 时调用 onRestoreInstanceState() 但仅当且仅当:
它被操作系统杀死了。 “这种情况发生在:
- 设备方向改变(您的 Activity 被销毁并重新创建)
- 您的前面还有另一个 Activity,在某些时候操作系统会终止您的 Activity 以释放内存(例如)。下次当你开始你的 Activity 时 onRestoreInstanceState() 将被调用。”
所以如果你在你的 Activity 中并且你在设备上点击返回按钮,你的 Activity 就完成了()并且下次你启动你的应用程序时它会再次启动(听起来像重新 -已创建,不是吗?)但这次没有保存状态,因为您在点击返回按钮时故意退出了它。
关于android - onSaveInstanceState() 和 onRestoreInstanceState(Parcelable state) 没有被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12327348/