Android Checkbox preference

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
Log.i("LOG", String.valueOf(sp.getBoolean("key", false)));

Simplest way i found of getting value if item is pressed. If log is:

I/LOG: true

Checkbox is pressed

I/LOG: false

Checkbox is not selected

Hope this answers your question.


You need to add a listener to the Preference in your onCreate method

    final CheckBoxPreference checkboxPref = (CheckBoxPreference) getPreferenceManager().findPreference("checkboxPref");

    checkboxPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {            
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            Log.d("MyApp", "Pref " + preference.getKey() + " changed to " + newValue.toString());       
            return true;
        }
    }); 

You can cast the value of the checkbox into a boolean. This might be safer and more extensible than checking the toString() value.

final CheckBoxPreference checkboxPref = (CheckBoxPreference) getPreferenceManager().findPreference("checkboxPref");

checkboxPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {            
    public boolean onPreferenceChange(Preference preference, Object newValue) {
        if(newValue instanceof Boolean){
            Boolean boolVal = (Boolean)newValue;
        }
        return true;
    }
});