Question

I have a CheckBoxPreference defined as follows:

<CheckBoxPreference
    android:defaultValue="true"
    android:key="prefVisible"
    android:summary="@string/pref_visible_summary"
    android:title="@string/pref_visible" >
</CheckBoxPreference>

My application uses this preference to control the visibility of a view. When I first start my application (on a new wiped emulator) the view is not shown. However, when the I go to the preferences screen (activity) the checkbox is shown as checked.

Does this mean that the defaultValue attribute is not actually setting the preference but rather it's just setting the value of the checkbox if there is no underlying data (as would be the case on a brand new install). And does this also mean that the preference is set only after the user enters/exits the preferences screen (activity) for the first time, otherwise it's undefined?

Note that in order to get my app to work the way I intended it to work I relied on the default value argument to the preferences getter method as follows:

SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean isVisible = sharedPrefs.getBoolean("prefVisible", true); // default = true

This leaves me a bit confused as to why there are 2 ways to control the default value of a preference: defining it in the Xml or providing the default value in the getBoolean method.

Was it helpful?

Solution

No the preferences can be set if you call PreferenceManager.setDefaultValues. So if you call this when the first time the app is launched then your view will be shown.
You can read more at http://developer.android.com/guide/topics/ui/settings.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top