如何设置 ListPreference 的默认值 [英] How to set the Default Value of a ListPreference
问题描述
我需要在 Activity 启动时为 ListPreference 设置默认值.我已经尝试过 ListPreference.setDefaultvalue("value");
但它使列表的第一个条目成为默认值.我需要它,因为我必须检查一个条件并将满足该条件的值设置为默认值,所以我认为它不能从 xml 文件中完成(使用 android:defaultValue
)
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
)
例如,假设我在 arrays.xml 中有这个值数组:
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>
在 PreferenceScreen xml 中:
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.
推荐答案
您是否尝试过:
setValueIndex(int index);
这篇关于如何设置 ListPreference 的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!