Question

How I can programmatically get the default value of a ListPreference as it have defined in the XML?

Here is the snippet of my ListPreference:

    <ListPreference
        android:defaultValue="60"
        android:entries="@array/interval_entries"
        android:entryValues="@array/interval_values"
        android:key="interval"
        android:summary="@string/interval_summary"
        android:title="@string/interval_title" />

I have been through the docs but I have not found a way to get this. Maybe I have overlooked it.

Was it helpful?

Solution

For PreferenceActivity (deprecated with Fragment), try:

ListPreference lp = (ListPreference) this.findPreference(this.getString(R.string.my_key));
lp.getValue();

Where my_key is the key value assigned to this ListPreference. Note: This value is defined in strings.xml. If you have hard-coded your key with a literal string, then substitute my_key with whichever string you've given for the android:key tag. So, in your case, the codes will be:

ListPreference lp = (ListPreference) this.findPreference("interval");
lp.getValue();

OTHER TIPS

Are you trying to initially set the default value or reset it to default? Regardless have a look at:

PreferenceManager.setDefaultValues(this, R.xml.your_pref_xml, false);

and the documentation

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