gpt4 book ai didi

java - onCreate(Bundle savingInstanceState) 中创建的 Bundle 对象在哪里

转载 作者:行者123 更新时间:2023-12-02 03:30:11 26 4
gpt4 key购买 nike

在 Android 中,onCreate 方法将 savedInstanceState 作为 Bundle 对象的引用。我只想知道 Bundle 对象是在哪里以及如何创建的?

最佳答案

如果您将应用程序的状态保存在 bundle 中(通常是 onSaveInstanceState 中的非持久动态数据),则如果需要重新创建 Activity(例如,方向更改),则可以将其传回 onCreate,这样您就不需要不要丢失这些先前的信息。如果没有提供数据,savedInstanceState 为 null。

您需要重写 onSaveInstanceState(Bundle savingInstanceState) 并将要更改的应用程序状态值写入 Bundle 参数,如下所示:

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putBoolean("MyBoolean", true);
savedInstanceState.putDouble("myDouble", 1.9);
savedInstanceState.putInt("MyInt", 1);
savedInstanceState.putString("MyString", "Welcome back to Android");
// etc.
}

Bundle 本质上是一种存储 NVP(“名称-值对”)映射的方式,它将被传递到 onCreate() 和 onRestoreInstanceState(),您可以在其中提取值,如下所示:

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
double myDouble = savedInstanceState.getDouble("myDouble");
int myInt = savedInstanceState.getInt("MyInt");
String myString = savedInstanceState.getString("MyString");
}

关于java - onCreate(Bundle savingInstanceState) 中创建的 Bundle 对象在哪里,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38216219/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com