当屏幕旋转时,有没有办法保存代码中正在更改的变量?提前谢谢
答案 0 :(得分:1)
您可以在停止活动时将值保存到instanceState Bundle中,并在启动时恢复它。像这样:
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Read values from the "savedInstanceState"
}
@Override
protected void onSaveInstanceState(Bundle outState) {
// Save the values you need into "outState"
super.onSaveInstanceState(outState);
}
答案 1 :(得分:1)
扩展GSala的答案,这就是我如何做到的:
@Override
public void onSaveInstanceState(Bundle savedInstanceState){
String someString = "this is a string";
savedInstanceState.putString(CONSTANT_STRING, someString);
//declare values before saving the state
super.onSaveInstanceState(savedInstanceState);
}
然后在你的onCreate中你可以获得这样的值:
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addContentView(R.layout.view);
//Make sure to do this check otherwise someString will
//cause an error when your activity first loads!
if (savedInstanceState != null){
//Do whatever you need with the string here, like assign it to variable.
Log.d("XXX", savedInstanceState.getString(STRING_CONSTANT));
}
}
这样,您也不必覆盖onRestoreInstanceState。此外,这可以通过任何变量或对象来完成,而不仅仅是字符串。
有关详细信息,请参阅this documentation。