Reputation: 9114
I have a xml file (/res/xml/setting.xml) for PreferenceActivity:
<?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>
Then I have another xml file "/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>
See ListPreference in setting.xml, I want android:defaultValue
to be set with winter.png
. But I also don't want to be set with hardcoded/constant value in the xml, so I tried with various values such as "@array/background_values/0
", "@array/background_values[0]
", etc...but all failed.
So, the questions are:
android:defaultValue
is working?@array
syntax? I can't found any.Upvotes: 5
Views: 9123
Reputation: 716
1- Define a separate file for arrays (res/values/arrays.xml)
arrays.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- use this arrays in Preference xml file:
<?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>
Upvotes: 0
Reputation: 381
Use the index of the value you want from your array android:defaultValue="0"
The above code worked only because i am using numbers inside my string array values, it is not because of index.
Upvotes: 0
Reputation: 381
string-array
in XML, not to metion its items. defaultValue
will go to your shared prefereces file. If defaultValue
matches one of the items, it will be selected.BTW, you can change your items in string-array to reference to string to avoid hardcoding.
Upvotes: 1