How to set the Default Value of a ListPreference

2019-01-18 08:15发布

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.

10条回答
该账号已被封号
2楼-- · 2019-01-18 08:49

Just for the record if someone else has this problem:

setValueIndex(int X) is setting the value @ index X to the default value - so it is probably what you are looking for.

Set this value AFTER you added the Values! (stupid mistake but took me half an hour)

查看更多
Luminary・发光体
3楼-- · 2019-01-18 08:49
((ListPreference) findPreference("pref_language")).setValue(Locale
                .getDefault().getLanguage());

setValue() is ListPreference's method, and setDefaultvalue is Preference's method

查看更多
乱世女痞
4楼-- · 2019-01-18 09:04

or you can also try colour.setValue(mycolour);

查看更多
Bombasti
5楼-- · 2019-01-18 09:05

Use the xml attribute android:defaultValue="<VALUE>" in your list tag to set the default value.

Note: the <VALUE> is the actual value and not the index of string array.

If still its not working, try below steps.

  • Clear application data.
  • Uninstall and reinstall the app
  • Check the list preference, you will see the default value selected

Strange, I know but it worked in my case.

查看更多
登录 后发表回答