【发布时间】:2016-07-06 04:12:53
【问题描述】:
在 Android 中,onCreate 方法将 savedInstanceState 作为 Bundle 对象的引用。
我只想知道Bundle 对象是在哪里以及如何创建的?
【问题讨论】:
标签: java android android-activity oncreate
在 Android 中,onCreate 方法将 savedInstanceState 作为 Bundle 对象的引用。
我只想知道Bundle 对象是在哪里以及如何创建的?
【问题讨论】:
标签: java android android-activity oncreate
如果您将应用程序的状态保存在一个包中(通常是 onSaveInstanceState 中的非持久动态数据),如果需要重新创建活动(例如,方向更改),可以将其传递回 onCreate 以便您不必不要丢失此先验信息。如果未提供数据,则 savedInstanceState 为 null。
您需要重写 onSaveInstanceState(Bundle savedInstanceState) 并将您要更改的应用程序状态值写入 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");
}
【讨论】: