5

我有一个 PreferenceActivity 的 xml 文件 (/res/xml/setting.xml):

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
        <PreferenceCategory android:title="Main Settings">
            <ListPreference
                android:title="Background Image"
                android:summary="Set the background image"
                android:key="key_background"
                android:entries="@array/background"
                android:entryValues="@array/background_values" 
                android:defaultValue="winter.png" /> 
        </PreferenceCategory>
</PreferenceScreen>

然后我有另一个xml文件“/res/values/string.xml”:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string-array name="background">
        <item>Winter</item>
        <item>Desert</item>
    </string-array>

    <string-array name="background_values">
        <item>winter.png</item>
        <item>desert.png</item>
    </string-array>

</resources>

请参阅 setting.xml 中的 ListPreference,我想android:defaultValue设置为winter.png. 但我也不想在 xml 中设置硬编码/常量值,所以我尝试了各种值,例如“ @array/background_values/0”、“ @array/background_values[0]”等……但都失败了。

所以,问题是:

  1. 在其他 xml 中访问字符串数组资源项的正确语法是什么?
  2. 如何确定是否android:defaultValue正常工作?
  3. 有没有关于@array语法的文档?我找不到任何东西。
4

3 回答 3

1
  1. Android 开发人员无法在 XML 中引用资源string-array,更不用说它的项目。
  2. 您可以清除应用程序的数据,重新安装并打开应用程序,转到设置屏幕,然后defaultValue将转到您共享的首选项文件。如果defaultValue匹配其中一项,它将被选中。

顺便说一句,您可以将字符串数组中的项目更改为引用字符串以避免硬编码。

于 2012-04-18T09:38:37.017 回答
0

使用数组 android:defaultValue="0" 中所需值的索引

上面的代码之所以起作用,只是因为我在字符串数组值中使用了数字,而不是因为索引。

于 2012-04-18T08:14:16.870 回答
0

1-为数组定义一个单独的文件(res/values/arrays.xml)

数组.xml

<?xml version="1.0" encoding="utf-8"?
<resources>
<string-array name="settings_order_by_labels">
    <item>label1</item>
    <item>label2</item>
</string-array>

<string-array name="settings_order_by_values">
    <item>value1</item>
    <item>value2</item>
</string-array>
</resources>

2- 在 Preference xml 文件中使用这个数组:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
android:title="@string/settings_title">

<ListPreference
    android:defaultValue="value1"
    android:entries="@array/settings_order_by_labels"
    android:entryValues="@array/settings_order_by_values"
    android:key="order_by"
    android:title="Order By" />
</PreferenceScreen>
于 2017-09-24T10:26:23.227 回答