Android – Referencing a string in a string array resource with xml


I have preferences where you can enable/disable what items will show up on the menu. There are 17 items. I made a string array in values/arrays.xml with titles for each of these 17 items.

I have preferences.xml which has the layout for my preferences file, and I would like to reference a single item from the string array to use as the title.

How can I do this?

In the Android developer reference, I see how I can reference a single string with XML, but not how I can reference a string from an array resource in XML.

Best Solution

In short: I don't think you can, but there seems to be a workaround:.

If you take a look into the Android Resource here:

You see than under the array section (string array, at least), the "RESOURCE REFERENCE" (as you get from an XML) does not specify a way to address the individual items. You can even try in your XML to use "@array/yourarrayhere". I know that in design time you will get the first item. But that is of no practical use if you want to use, let's say... the second, of course.

HOWEVER, there is a trick you can do. See here:

Referencing an XML string in an XML Array (Android)

You can "cheat" (not really) the array definition by addressing independent strings INSIDE the definition of the array. For example, in your strings.xml:

<string name="earth">Earth</string>
<string name="moon">Moon</string>

<string-array name="system">

By using this, you can use "@string/earth" and "@string/moon" normally in your "android:text" and "android:title" XML fields, and yet you won't lose the ability to use the array definition for whatever purposes you intended in the first place.

Seems to work here on my Eclipse. Why don't you try and tell us if it works? :-)