Saving State of Multiple Checkboxes - Android

↘锁芯ラ 提交于 2021-02-19 07:32:48

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!