Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access <item> from <string-array> resource in an android XML?

Tags:

android

xml

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:

  1. What is the correct syntax for accesing an item of string-array resource in other xml?
  2. How to make sure if the android:defaultValue is working?
  3. Is there any documentation about the @array syntax? I can't found any.
like image 842
null Avatar asked Nov 14 '22 06:11

null


1 Answers

  1. Android Developers gives no way for resource reference to string-array in XML, not to metion its items.
  2. You can clear your app's data, reinstall and open your app, go to your settings screen, then the 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.

like image 156
Dot Cink Avatar answered Nov 16 '22 04:11

Dot Cink