我正在为java类构建一个内存游戏应用程序,我需要保存通过设备旋转显示哪些单词...需要保存并传递给新的onCreate()方法的小部件是按钮小部件我使用setText显示正在显示的单词....我可以保存并传递应用程序的整个状态...这是我的代码显然不起作用,我希望我能得到一些见解..谢谢......这是我的代码..
private Bundle myBundle = new Bundle();
.....
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_eight);
if(savedInstanceState != null) {
savedInstanceState = myBundle;
}
......
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
myBundle = savedInstanceState;
}
答案 0 :(得分:0)
你有向后使用Bundle的语义。你不想要保存Bundle(或覆盖它)。只需使用它将您自己的状态变量序列化到其中即可。例如,如果要在旋转之间保留两个整数变量和一个字符串(以便稍后可以使用这些成员重新初始化视图),则可以执行以下操作:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_eight);
if(savedInstanceState != null) {
// Restore our member variables that represent activity state right here from the passed in Bundle.
_x = savedInstanceState.getInt("MyApp.X", 0);
_y = savedInstanceState.getInt("MyApp.Y", 0);
_name = savedInstanceState.getString("MyApp.NAME", "player");
// not shown - initializing the view elements with the initialized member variables.
}
......
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// save our activity state by adding our member variables that represent activity state into the Bundle.
savedInstanceState.putInt("MyApp.X", _x);
savedInstanceState.putInt("MyApp.Y", _y);
savedInstanceState.putString("MyApp.NAME", _name);
// call the parent method *after* you have saved your state
super.onSaveInstanceState(savedInstanceState);
}
Bundle还支持简单类型的数组。
答案 1 :(得分:0)
在onSaveInstanceState方法中,添加要保存的值,如下所示
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString("key","your string here");
}
并在oncreate里面
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if( savedInstanceState != null ) {
System.out.println(savedInstanceState .getString("key"));
}
}