Search code examples
androidandroid-preferencescheckboxpreference

How to handle checkbox status manually?


I need to control a CheckBoxPreference manually; I have to check a condition in my own data to determine if the preference can be set or not.

How can I do it? My current code is as follows, but it doesn't seem to work.

CheckBoxPreference buyPref = (CheckBoxPreference) findPreference("pref_billing_buy");
buyPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {   
   if (something) {
     return true; // checkbox should be checked
   } else {
     return false; // checkbox should be unchecked
   }

Should I always return false and then use

buyPref.setChecked(true);

Solution

  • I think you want something like this:

    final CheckBoxPreference buyPref = (CheckBoxPreference) findPreference("logs");
    buyPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener()
    {
        @Override
        public boolean onPreferenceChange(final Preference preference,
            final Object newValue)
        {
            boolean condition = false;
            // set condition true or false here according to your needs.
            buyPref.setChecked(condition);
            Editor edit = preference.getEditor();
            edit.putBoolean("pref_billing_buy", condition);
            edit.commit();
            return false;
        }
    });
    

    You want to always return false from this so that Android doesn't attempt to write the preference itself. See the documentation for OnPreferenceChangeListener for more info.

    Note that all of this will happen on the UI thread, so if you need to do anything long-running, I would throw it in an AsyncTask with a ProgressDialog so that the user doesn't get frustrated.