Android 保存按钮的状态
我正在吃晚饭 关闭模拟器然后再次运行后,保存按钮状态时出现问题。 以下是onCreate和onDestory中的代码Android 保存按钮的状态,android,Android,我正在吃晚饭 关闭模拟器然后再次运行后,保存按钮状态时出现问题。 以下是onCreate和onDestory中的代码 @Override protected void onDestroy() { super.onDestroy(); ViewGroup v=(ViewGroup) findViewById(R.id.GridLayout1); SharedPreferences setting= getSharedPreferences("MyPrefs",0);
@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(){
super.ondestory();
ViewGroup v=(ViewGroup)findViewById(R.id.GridLayout1);
SharedReferences设置=GetSharedReferences(“MyPrefs”,0);
SharedReferences.Editor=setting.edit();
对于(int i=2;i<((视图组)v).getChildCount();i++){
视图childView=((视图组)v).getChildAt(i);
int resID=childView.getId();
按钮btn=(按钮)findViewById(剩余);
putString(“value”,btn.getText().toString());
commit();
}
}
你是对的
您正在覆盖onDestroy
中for循环的每次迭代中的键值
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循环的每次迭代中的键值
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()
。改用onPause()
<代码>onDestroy()
仅在您的活动finish()
时才可靠。主要问题是,您在循环中只保存了一个值,这将是最后一个值。我怀疑您打算为每个按钮使用一个值。不要使用onDestroy()
。改用onPause()
<代码>onDestroy()仅在您的活动finish()
时才可靠。主要问题是,您在循环中只保存了一个值,这将是最后一个值。我怀疑您打算为每个按钮使用一个值。+1用于将按钮ID用作键。美好的如果您添加了onCreate()的修改,这将是一个很好的答案+1用于将按钮ID用作键。美好的如果您添加了onCreate()的修改,这将是一个很好的答案!