java 什么是“savedInstanceState”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37152601/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 02:14:43  来源:igfitidea点击:

What is 'savedInstanceState'?

javaandroidandroid-studiosdk

提问by amitoz

I am new to Android Development but I have some knowledge of OOP concepts. I am trying to learn Android from Java perspective.

我是 Android 开发的新手,但我对 OOP 概念有一些了解。我正在尝试从 Java 的角度学习 Android。

My code

我的代码

I understand that savedInstanceStateinside onCreate()on line 9 is the declaration of Bundle class. On line 10 we are calling the onCreate()method from the super class.

我知道第 9 行savedInstanceState里面onCreate()是 Bundle 类的声明。在第 10 行,我们onCreate()从超类调用方法。

Here is what I don't unterstand:On line 10 we pass savedInstanceStateitself as a parameter to the onCreate()method. This doesn't make sense to me as I would expect to pass an object which is of the Bundletype, but instead of that we pass a reference not an object of type Bundle to the method.

这是我不明白的:在第 10 行,我们将savedInstanceState本身作为参数传递给onCreate()方法。这对我来说没有意义,因为我希望传递一个Bundle类型的对象,但我们将引用而不是 Bundle 类型的对象传递给方法。

回答by Max

The savedInstanceState is a reference to a Bundle object that is passed into the onCreate method of every Android Activity.

savedInstanceState 是对传递到每个 Android Activity 的 onCreate 方法的 Bundle 对象的引用。

The onCreate() expects to be called with a Bundle as parameter so we pass savedInstanceState.

onCreate() 期望以 Bundle 作为参数被调用,因此我们传递了 savedInstanceState。

Activities have the ability, under special circumstances, to restore themselves to a previous state using the data stored in this bundle. If there is no available instance data, the savedInstanceState will be null.

在特殊情况下,活动能够使用存储在此包中的数据将自身恢复到以前的状态。如果没有可用的实例数据,则savedInstanceState 将为空。

For example, the savedInstanceState will always be null the first time an Activity is started, but may be non-null if an Activity is destroyed during rotation, because onCreate is called each time activity starts or restarts.

例如,第一次启动 Activity 时,savedInstanceState 将始终为 null,但如果 Activity 在轮换期间被销毁,则可能为非 null,因为每次 Activity 启动或重新启动时都会调用 onCreate。

Hope it helps

希望能帮助到你

回答by Atahar Hossain

When an activity is re-initialized ,then the savedInstance contains the most recent data , specially contains data of the activity's previous initialization part.

当一个活动被重新初始化时,那么savedInstance 包含最近的数据,特别是包含活动之前初始化部分的数据。

Actually, when an activity is killed it saved its states so that when user back to this activity , it can restore its states

实际上,当一个活动被杀死时,它会保存它的状态,这样当用户回到这个活动时,它可以恢复它的状态