保存按钮状态
问题描述:
我遇到 保存按钮状态的问题一旦关闭模拟器然后再次运行。 继承人中的onCreate代码和onDestory保存按钮状态
@Override
protected void onDestroy() {
super.onDestroy();
ViewGroup v=(ViewGroup) findViewById(R.id.GridLayout1);
SharedPreferences setting= getSharedPreferences("MyPrefs",0);
SharedPreferences.Editor editor=setting.edit();
for(int i=2; i < ((ViewGroup)v).getChildCount(); i++) {
View childView = ((ViewGroup)v).getChildAt(i);
int resID = childView.getId();
Button btn = (Button) findViewById(resID);
editor.putString("value",btn.getText().toString());
editor.commit();
}
}
答
你是正确的。
您在覆盖onDestroy
for循环的每次迭代中覆盖键value
的值。
for(int i=2; i < ((ViewGroup)v).getChildCount(); i++) {
View childView = ((ViewGroup)v).getChildAt(i);
int resID = childView.getId();
Button btn = (Button) findViewById(resID);
editor.putString("value",btn.getText().toString());
editor.commit();
}
你必须每个值存储与独特键,每个对应一个唯一的按钮,然后在你的onCreate
单独检索每个。
要选择你的唯一键,我建议使用按钮的ID。
for(int i=2; i < ((ViewGroup)v).getChildCount(); i++) {
View childView = ((ViewGroup)v).getChildAt(i);
int resID = childView.getId();
Button btn = (Button) findViewById(resID);
editor.putString(String.valueOf(btn.getId()),btn.getText().toString());
editor.commit();
}
+1
使用按钮ID作为键。尼斯。如果你添加了onCreate()的修改,这将是一个很好的答案! – Simon
不要使用'onDestroy()'。改用'onPause()'。如果你完成()你的活动,'onDestroy()'是唯一可靠的。主要的问题是你只在你的循环中保存一个值,这将是最后一个值。我怀疑你的意思是为每个按钮使用一个值。 – Simon