How to set the Default Value of a ListPreference

Gnufabio picture Gnufabio · Mar 4, 2011 · Viewed 49.6k times · Source

i need to set the defult value for a ListPreference when the Activity starts. I've tried with ListPreference.setDefaultvalue("value"); but it makes the firts Entry of the List as default. I need it because i must check a condition and set as default the value which satisfies that condition, so I think it can't be done from the xml file (with android:defaultValue)

For example, suppose I have this array of values in the arrays.xml:

<string-array name="opts">
    <item>red</item>
    <item>green</item>
    <item>blue</item>
</string-array>

<string-array name="opts_values">
    <item>1</item>
    <item>2</item>
    <item>3</item>
</string-array>

In the PreferenceScreen xml:

<ListPreference
    android:title="Colour select"
    android:summary="Select your favourite"
    android:key="colour"
    android:entries="@array/opts"
    android:entryValues="@array/opts_values" />

In the Activity I'd like to do something like this:

String mycolour;
if (something) {
    mycolour="1";
} else {
    mycolour="2";
}
ListPreference colour = (ListPreference) findPreference ("colour");
colour.setDefaultValue(mycolour);

But it doesn't work, because it makes the first choice as default. Could you explain me how to make another one as default? Thanks.

Answer

Md. Naushad Alam picture Md. Naushad Alam · Jul 7, 2013

You don't need to programmatically handle the default value of ListPreferences. You can do this in xml setting file. Below is an example

<string-array name="opts">
    <item>red</item>
    <item>green</item>
    <item>blue</item>
</string-array>

<string-array name="opts_values">
    <item>1</item>
    <item>2</item>
    <item>3</item>
</string-array>

...

<ListPreference
    android:title="Colour select"
    android:summary="Select your favourite"
    android:key="colour"
    android:entries="@array/opts"
    android:entryValues="@array/opts_values"
    android:defaultValue="2" />

here I selected 2 as a default value. Remember defaultvalue will be opts_values element.