【发布时间】:2012-05-31 18:35:50
【问题描述】:
我正在使用 getLastNonConfigurationInstance() 来保存对象,同时在我的活动中更改方向。现在它已被弃用。最好的替代方法是什么?文档说“使用片段”。但我需要使用活动。
【问题讨论】:
标签: android android-orientation
我正在使用 getLastNonConfigurationInstance() 来保存对象,同时在我的活动中更改方向。现在它已被弃用。最好的替代方法是什么?文档说“使用片段”。但我需要使用活动。
【问题讨论】:
标签: android android-orientation
要保存状态,请使用onSaveInstanceState(Bundle savedInstanceState)。您可以在onCreate 或onRestoreInstanceState(Bundle savedInstanceState) 中恢复保存的状态。
@Override
public void onSaveInstanceState(Bundle 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", "Hello Android");
super.onSaveInstanceState(savedInstanceState);
}
Bundle 本质上是一种存储“键值对”映射的方式, 它将被传递给 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");
}
【讨论】: