当Activity启动时,我需要设置ListPreference的默认值。我尝试使用ListPreference.setDefaultvalue("value");
,但这会将列表的第一个条目设置为默认值。我需要这样做是因为我必须检查条件并将满足该条件的值设置为默认值,因此我认为不能从xml文件中完成(使用android:defaultValue
)。
例如,假设我在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中:<ListPreference
android:title="Colour select"
android:summary="Select your favourite"
android:key="colour"
android:entries="@array/opts"
android:entryValues="@array/opts_values" />
在Activity中,我想要做这样的事情:
String mycolour;
if (something) {
mycolour="1";
} else {
mycolour="2";
}
ListPreference colour = (ListPreference) findPreference ("colour");
colour.setDefaultValue(mycolour);
但它不起作用,因为它使第一个选择默认。你能解释一下如何将另一个选项设为默认吗?谢谢。
android:defaultValue="1"
),而不是从 0 开始。 - Kenny Wordenstring-array
以外的任何内容,当它试图查找相应的项目时,您将会得到一个错误提示。请见 https://dev59.com/GnXYa4cB1Zd3GeqP_OCc#25355756。 - lucidbrot