我正在使用getLastNonConfigurationInstance()在我的活动中更改方向时保存对象。现在它被弃用了。什么是最佳替代方式?文档说“使用片段”。但我需要使用活动。
答案 0 :(得分:3)
要保存状态,请使用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");
}