令人困惑的 Android Activity 生命周期行为
我通过重写每个生命周期方法编写了一个简单的程序,除了 onRestoreInstanceState(Bundle savingInstanceState)
之外,一切都按我的预期工作。
我重写了该方法,
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
Toast.makeText(getBaseContext(), "onRestoreInstanceState - Activity1 ", Toast.LENGTH_SHORT).show();
}
但它永远不会被调用。
我也覆盖了 onSaveInstanceState(Bundle outState)
,我可以看到系统调用它,但看不到 onRestoreInstanceState(Bundle savingInstanceState)
。当我按后退按钮左右时,我可以看到系统调用 onRestore()
、OnStart()
和 onResume()
,并且UI(仅两个按钮)正确显示。
不调用onRestoreInstanceState(Bundle savingInstanceState)怎么可能恢复UI?我只做 setContentView(R.layout.main)
是 onCreate(savedInstanceState)
。那么它如何在不调用 onCreate()
或 onRestoreInstanceState()
的情况下恢复 UI?
非常感谢有人对此有所了解。
谢谢。
I did a simple program by overriding each of the lifecycle methods and everything works as I'd expect, except for onRestoreInstanceState(Bundle savedInstanceState)
.
I overrode the method as
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
Toast.makeText(getBaseContext(), "onRestoreInstanceState - Activity1 ", Toast.LENGTH_SHORT).show();
}
But it never gets called.
I overrode onSaveInstanceState(Bundle outState)
too and I can see the system calling it, but never the onRestoreInstanceState(Bundle savedInstanceState)
. When I press back button or so, I can see that the system calls onRestore()
, OnStart()
and onResume()
, and the UI (just two buttons) are displayed correctly.
How is it possible that the UI is restored without calling onRestoreInstanceState(Bundle savedInstanceState)
? I only do setContentView(R.layout.main)
is onCreate(savedInstanceState)
. So how does it restore the UI without calling either onCreate()
or onRestoreInstanceState()
?
Would really appreciate somebody shedding some light on this.
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里的文档有点令人困惑,但我认为这个方法只是作为 onCreate 处理存储状态的一种替代,发生在循环的后期。仅当活动被销毁并使用状态重新创建时才会调用它;这最常发生在方向改变期间。它无意于处理活动之间的普通转换期间的状态。
另请参阅onSaveInstanceState () 和 onRestoreInstanceState ()
The documentation here is a bit confusing, but I think this method is only intended as a kind of stand-in for onCreate's handling of stored state, occurring later in the cycle. It's only called if the activity is destroyed and re-created with state; this would most commonly happen during an orientation change. It's not intended to handle state during ordinary transitions between activities.
See also onSaveInstanceState () and onRestoreInstanceState ()