androidsharedpreferencescheckboxpreference

Make CheckBoxPreference store a String ("true"/"false") instead of a Boolean in SharedPreferences


I have a PreferentFragment whose content is loaded from a .xml file containing a CheckBoxPreference

    <CheckBoxPreference
          android:title="@string/pref_secure_conn"
          android:key="enable_secure_connection"
          android:defaultValue="false"/>

As you know, when the user interacts with this Preference, the SharedPreferences object is automatically updated so that the android:key now contains the proper Boolean.

However, I would like to use a String instead of a Boolean: Is there any way to make CheckBoxPreference use String-valued values instead of Boolean ones, so that I can later call getString with that key?

Currently, I am just listening 'onSharedPreferenceChanged' and manually changuing it, but maybe there is a better way. (Another obvious fix would be to use getBoolean instead of getString when this value is needed, but let's assume I cannot do that)


Solution

  • The easiest way i could think of is inheriting the CheckBoxPreference and save the Preference redundant:

    package com.example.preferencestest;
    
    import android.content.Context;
    import android.content.SharedPreferences;
    import android.preference.CheckBoxPreference;
    import android.util.AttributeSet;
    
    public class StringCheckBoxPreference extends CheckBoxPreference {
        public StringCheckBoxPreference(Context context) { super(context); }
        public StringCheckBoxPreference(Context context, AttributeSet attrs) { super(context, attrs); }
        public StringCheckBoxPreference(Context context, AttributeSet attrs,
                int defStyle) { super(context, attrs, defStyle); }
    
        @Override
        public void setChecked(boolean checked) {
            super.setChecked(checked);
            SharedPreferences p = getSharedPreferences();
            SharedPreferences.Editor e = p.edit();
            e.putString(getKey()+"asString", String.valueOf(checked));
            e.apply();
        }
    }
    

    you may add this class to your PreferencesActivity xml like this:

    <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
    
        <com.example.preferencestest.StringCheckBoxPreference
            android:defaultValue="true"
            android:key="myCheckBox"
            android:summary="@string/pref_description_social_recommendations"
            android:title="@string/pref_title_social_recommendations"
        />
    
        <CheckBoxPreference
            android:defaultValue="true"
            android:key="example_checkbox"
            android:summary="@string/pref_description_social_recommendations"
            android:title="@string/pref_title_social_recommendations" />