hpique hpique - 1 year ago 107
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 Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download