我正在开发一个应用程序。一页中有许多复选框。我想在退出页面时保存CheckBox的状态。我使用SharedPreferrences来保存。代码是这样的:
checkbox1.setOnCheckedChangeListener(new OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
// TODO Auto-generated method stub
Editor editor = getSharedPreferences("syllabus", 0).edit();
editor.putBoolean("cbx1_ischecked", isChecked);
editor.commit();
}
});
checkbox2.setOnCheckedChangeListener(new OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
// TODO Auto-generated method stub
Editor editor = getSharedPreferences("syllabus", 0).edit();
editor.putBoolean("cbx2_ischecked", isChecked);
editor.commit();
}
});
当我离开此页面时,又回来了。所有复选框状态都不会被选为默认状态。为什么呢?
答案 0 :(得分:2)
您正在保存值,但是您必须恢复它们,您的活动就是这样开始的:
SharedPreferences prefs = getSharedPreferences("syllabus", 0);
checkbox1.setChecked(prefs.getBoolean("cbx1_ischecked" ,false));
checkbox2.setChecked(prefs.getBoolean("cbx2_ischecked" ,false));
答案 1 :(得分:0)
试试这个
boolean check1,check2;
checkbox1.setOnCheckedChangeListener(new OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
// TODO Auto-generated method stub
check1=isChecked;
}
});
checkbox2.setOnCheckedChangeListener(new OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
// TODO Auto-generated method stub
check2=isChecked;
}
});
//store boolean only once when you leave the activity
Editor editor = getSharedPreferences("syllabus", 0).edit();
editor.putBoolean("cbx1_ischecked", check1);
editor.putBoolean("cbx2_ischecked", check2);
editor.commit();
In onCreate()
SharedPreferences prefs = getSharedPreferences("syllabus", 0);
checkbox1.setChecked(prefs.getBoolean("cbx1_ischecked" ,false));
checkbox2.setChecked(prefs.getBoolean("cbx2_ischecked" ,false));