hpique hpique - 12 days ago 7
Android Question

Default value of Android preference

How do you get the default value of an Android preference defined in XML? I don't want to repeat the definition of the default value in both the code and the preferences XML.

Answer

You can define default value in resources (/values/bool.xml):

<resources>
    <bool name="mypreference_default">true</bool>
</resources>

Use the value in the preferences.xml:

<CheckBoxPreference
    android:defaultValue="@bool/mypreference_default"
    android:key="mypreference"
    android:title="@string/mypreference_title" />

Then use in code:

SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(context);
Boolean value = context.getResources().getBoolean(R.bool.mypreference_default);
Boolean b = p.getBoolean("mypreference", value);