How to save state of CheckBox after exit?

本小妞迷上赌 提交于 2019-12-23 04:52:45

问题


In my app ,one interface has some checkBoxes,I wish after I exit the interface, the CheckBoxes should maintain the state.So next time I enter it can show what I have done last time.I have used SharedPreferrences to achieve this.

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();
    }

});

But it doesn't work. when I return to this page, All checkBox show state that "every item is unselected ".

How can I realize the function I wish?


回答1:


After put date getSharedPreferences, You have to initialize your checkboz state with this data in onCreate, like below

// onCreate

SharedPreferences settings = getSharedPreferences("syllabus", 0);
Boolean isChecked = settings.getBoolean("cbx1_ischecked", false);
checkbox1.setChecked(isChecked );



回答2:


Your values are saved to SharedPreferences, but that doesn't mean they are automatically restored to the corresponding checkboxes. You need to read them from SharedPreferences and set your checkboxes when your activity starts, as @talhakosen mentioned.

Besides, you don't need to write your values to SharedPreferences every time they change. It would be enough to store them when user leaves your activity, i.e. in onStop() method.



来源:https://stackoverflow.com/questions/13560833/how-to-save-state-of-checkbox-after-exit

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