复选框Android的节能状态,如果退出应用程序 [英] Android saving state of checkbox if exit app

查看:112
本文介绍了复选框Android的节能状态,如果退出应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有5 checkboxs和被点击时,他们一个抽象类来使用onCheckedChangeListener true或false设置一个布尔值。例如:

I have 5 checkboxs and when they are clicked they set a boolean in an abstract class to true or false using a onCheckedChangeListener. Example:

checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener(){

            @Override
            public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) 
            {
                if(isChecked)
                {
                    CheckboxData.checked = true;
                }
                else if(!isChecked)
                {
                    CheckboxData.checked = false;
                }

            }

        });

然而,当我离开应用程序,并返回复选框被再也没有点击,但布尔值仍然如​​此。我怎样才能使应用程序记住的复选框被点击?如果我只是检查布尔值的主要活动的onCreate并设置checkboxs托运或没有,那么还是有使应用程序记住checkboxs状态的更好/更快的方式?

However when I leave the app and return the checkboxes are not clicked anymore, yet the boolean values are still true. How can I make the app remember that the check boxes are clicked.? Should I just check the boolean values in the main activity onCreate and set the checkboxs to checked or not then or is there a better/faster way to make the app remember the checkboxs states?

刚刚在主要活动添加了这个onCreate方法:

Just added this in the main activities onCreate method:

      if(CheckboxData.checked)
    {
        CheckBox checkbox = (CheckBox) findViewById(R.id.checkbox);
        checkbox.setChecked(true);
    }

但它确实没有什么

But it does nothing

推荐答案

活动 GET 摧毁选中复选框国家如果属实,并添加共享preference复选框状态

when Activity get destroyed check the checkbox state if true , and add the checkbox state in shared Preference

     @Override
    public void onDestroy() {

    if(CheckboxData.checked){
     SharedPreferences prefs = getSharedPreferences("private preference", Context.MODE_PRIVATE);
            prefs.edit()
                .putBoolean("CheckboxData",true)
                .commit();
   }
    super. onDestroy();

   }

活动推出回来,在的onCreate 为您在preference,如果该复选框状态真正使复选框

And when Activity is launched back, In onCreate check for the checkbox state in preference and if true enable the checkbox

  SharedPreferences prefs = getSharedPreferences("private preference", Context.MODE_PRIVATE);

  boolean isChecked = prefs.getBoolean("CheckboxData",false);
  if(isChecked)
  checkBoxView.setChecked(true) 

这篇关于复选框Android的节能状态,如果退出应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆