我正在使用sharedpreferences開發任務列表應用程序。但它不保存複選框狀態。我想在用戶點擊複選框時保存。用戶退出應用程序並再次查看它已經更新狀態。如何保存複選框狀態? 這裏是我的代碼(已經被固定,工作)SharedPreferences不保存複選框狀態
public class TaskList extends Activity {
CheckBox cb1, cb2, cb3, cb4;
Boolean checked = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_tasks);
super.onCreate(savedInstanceState);
findID();
cb1 = (CheckBox) findViewById(R.id.checkBox1);
boolean isChecked = getBooleanFromPreferences("isChecked");
Log.i("start", "" + isChecked);
cb1.setChecked(isChecked);
cb1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton view, boolean isChecked) {
Log.i("boolean", "" + isChecked);
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();
}
private boolean getBooleanFromPreferences(String key) {
SharedPreferences sharedPreferences = this
.getPreferences(Activity.MODE_PRIVATE);
Boolean isChecked = sharedPreferences.getBoolean(key, false);
return isChecked;
}
private void findID() {
cb1 = (CheckBox) findViewById(R.id.checkBox1);
cb2 = (CheckBox) findViewById(R.id.checkBox2);
cb3 = (CheckBox) findViewById(R.id.checkBox3);
cb4 = (CheckBox) findViewById(R.id.checkBox4);
}
}
我明白你只想要實現這個行爲CB1 – zozelfelfo 2014-09-26 09:59:05
這是爲什麼保存PREF註釋掉爲什麼它引用的未知類'Settings'行? – wvdz 2014-09-26 10:00:08
是的,我只想爲cb1 – bee 2014-09-26 10:00:17