hpique hpique - 3 months ago 36
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.


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

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

Use the value in the preferences.xml:

    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);