Android ToggleButton always check

て烟熏妆下的殇ゞ 提交于 2019-12-20 07:08:53

问题


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

 toggle.setOnCheckedChangeListener(new OnCheckedChangeListener(){
         public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)

if(isChecked){             
    SharedPreferences.Editor editor = getSharedPreferences("SharedPrefName", MODE_PRIVATE).edit();
   editor.putBoolean("check", true);
      editor.commit();

    } 
else   {
  SharedPreferences.Editor editor = getSharedPreferences("SharedPrefName", MODE_PRIVATE).edit();
   editor.putBoolean("nocheck", false);
   editor.commit();
}
}});

But when I test this, it is always set to check in OnCreate() I added this:

SharedPreferences preferences = getSharedPreferences("SharedPrefName", MODE_PRIVATE);
    boolean value1 = preferences.getBoolean("check", true);  

    if (value1 = sharedPrefs.getBoolean("check", true)){
        psw.setChecked(value1);
    }else  {
        psw.setChecked(false);
    }

回答1:


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


来源:https://stackoverflow.com/questions/21095297/android-togglebutton-always-check

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