繁体   English   中英

在onCreate(Bundle savedInstanceState)中创建捆绑对象的位置在哪里

[英]Where is Bundle object created in onCreate(Bundle savedInstanceState)

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

如果您将应用程序的状态保存在捆绑包中(通常在onSaveInstanceState中为非持久性动态数据),那么如果需要重新创建活动(例如,方向更改),则可以将其传递回onCreate,以免丢失此先验信息。 如果未提供任何数据,则saveInstanceState为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");
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM