在onCreate中创建的Bundle对象在哪里(Bundle savedInstanceState)

时间:2016-07-06 04:12:53

标签: java android android-activity oncreate

在Android中,onCreate方法将savedInstanceState作为Bundle对象的引用。 我只是想知道Bundle对象的创建位置和方式?

1 个答案:

答案 0 :(得分:2)

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

您需要覆盖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");
}