androidcheckboxpreference

How to check CheckBoxPreference is checked or not?


I have a Setting Page where I have added CheckBoxPreference I need to check whether the checkbox is checked or not? My code is :

<PreferenceCategory android:title="Google Maps">

    <CheckBoxPreference
        android:defaultValue="true"
        android:summary="@string/markerSummary"
        android:title="@string/markerTitle"
        android:key="@string/markerKey" />

</PreferenceCategory>

In settingActivity.java

Preference DragPref = findPreference(getString(R.string.markerKey));
        DragPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                boolean checked = Boolean.valueOf(newValue.toString());
                return false;
            }
        });

This code is always returning false; And after adding above code its not changing to false. Can you help me how to achieve this?


Solution

  • use this, hope it will solve your problem.

    Preference DragPref = findPreference(getString(R.string.markerKey));
        DragPref.setOnPreferenceChangeListener(new  Preference.OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                boolean checked = (Boolean) newValue;
                return true; 
               // Note: return true to update the state of the Preference with the new value. If you want to disallow the change return false
            }
        });