问题
I am able to save the state of a Single CheckBox but how do i save All the Five CheckBoxes in my Activity?
checkBox = (CheckBox) findViewById(R.id.checkBox1);
boolean isChecked = getBooleanFromPreferences("isChecked");
Log.i("start",""+isChecked);
checkBox.setChecked(isChecked);
checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton view, boolean isChecked) {
Log.i("boolean",""+isChecked);
Settings.this.putBooleanInPreferences(isChecked,"isChecked");
}
});
}
public void putBooleanInPreferences(boolean isChecked,String key){
SharedPreferences sharedPreferences = this.getPreferences(Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(key, isChecked);
editor.commit();
}
public boolean getBooleanFromPreferences(String key){
SharedPreferences sharedPreferences = this.getPreferences(Activity.MODE_PRIVATE);
Boolean isChecked = sharedPreferences.getBoolean(key, false);
return isChecked;
回答1:
For second checkbox do the following
boolean isCheckedTwo = getBooleanFromPreferences("isCheckedTwo");
checkBox2.setChecked(isCheckedTwo );
checkBox2.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton view, boolean isChecked) {
Settings.this.putBooleanInPreferences(isChecked,"isCheckedTwo");
}
});
and similarly for the rest
回答2:
Use a Arraylist to store the state of all the checkboxes
回答3:
Put each one with different name. and remember the key comes first not the value. Call your save method each time with different name
来源:https://stackoverflow.com/questions/22761624/saving-state-of-multiple-checkboxes-android