简体   繁体   English

如何保存复选框状态? -安卓

[英]How to save the checkbox state? - android

Ya there are plenty of questions and answers about this stuff in the net but i just can't figure out how to save the checkbox state using sharedpreference. 是的,网络上对此有很多疑问和答案,但是我只是不知道如何使用sharedpreference保存复选框状态。 Someone just help me with the coding part which i was not able to do. 有人只是帮我解决我无法做到的编码部分。

ch = (CheckBox) findViewById(R.id.checkBox1);

    ch.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
        if(ch.isChecked())
                {
            Toast.makeText(getApplicationContext(), "Check", Toast.LENGTH_SHORT).show();
            }
        else
        {
            Toast.makeText(getApplicationContext(), "Uncheck", Toast.LENGTH_SHORT).show();
        }}
    });
    }

Just create SharedPrefrences and Add value using .putBoolean() 只需创建SharedPrefrences并使用.putBoolean()添加值

 if(ch.isChecked()){             

    SharedPreferences settings = getSharedPreferences(PREFRENCES_NAME, 0);
    settings.edit().putBoolean("check",true).commit();

}

I think answer you already knew, let me clear your way, 我想你已经知道答案了,让我澄清一下,

  • make a boolean field in table 在表中创建一个布尔字段
  • set its value true when CheckBox is checked else false 选中CheckBox时将其值设置为true,否则设置为false

Next time when you are loading the activity, just read the field value and set Checkbox's status accordingly. 下次加载活动时,只需读取字段值并相应设置Checkbox的状态即可。

if(ch.isChecked())
{
    SharedPreferences preferences = context.getSharedPreferences("prefs_name", Context.MODE_PRIVATE);
    preferences.edit().putBoolean("checked", True).commit();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM