Android ToggleButton always check

后端 未结 1 877
梦如初夏
梦如初夏 2021-01-28 03:10

I want to store in SharedPreferences if the toggle button is Checked or uncheck.

 toggle.setOnCheckedChangeListener(new OnCheckedChangeListener(){
         publi         


        
相关标签:
1条回答
  • 2021-01-28 03:52

    In the OnCheckedChangeListener, if the checkbox is checked, you save check = true. When loading, the if will always be true, since you are comparing the value to itself (or the default which you gave as true) so it checks the box.

    If the checkbox is not checked, you save nocheck = false. When loading, there is no check preference (or it has the previously saved true value) so the default true is loaded.

    Fixing your code:

    Listener method body:

    SharedPreferences.Editor editor = getSharedPreferences("SharedPrefName", MODE_PRIVATE).edit();
    editor.putBoolean("check", ischecked);
    editor.commit();
    

    Loading code (replace the second snippet with this):

    psw.setChecked(preferences.getBoolean("check", false));
    
    0 讨论(0)
提交回复
热议问题