String-array should be placed in the file /res/values/arrays.xml
and not /res/values/strings.xml
Each element of the array should not be hard-coded in the array, but instead use a reference to a string defined in /res/values/strings.xml
.
To explain, I'll use an example from this tutorial .
First define strings in /res/values/strings.xml
.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string
name="app_name">Choose Your Own</string>
<string
name="race_orc">Orc</string>
<string
name="race_elf">Elf</string>
<string
name="race_troll">Troll</string>
<string
name="race_human">Human</string>
<string
name="race_halfling">Halfling</string>
<string
name="race_goblin">Goblin</string>
</resources>
Then, using these strings , set the array to /res/values/arrays.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array
name="races_array">
<item>@string/race_goblin</item>
<item>@string/race_orc</item>
<item>@string/race_elf</item>
<item>@string/race_human</item>
<item>@string/race_troll</item>
<item>@string/race_halfling</item>
</string-array>
</resources>
In Java to get a reference to string-array use:
String[] cRaces = getResources().getStringArray(R.array.races_array);
In xml, for example, a Spinner can use it this way:
<Spinner
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:id="@+id/spinnerOfCharacterRaces"
android:entries="@array/races_array">
</Spinner>
To access a particular item in the array will not use the array but the string defined in /res/values/strings.xml
.
This allows you to use the name assigned to the string and not an index.
For example on a button:
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/race_orc" />
Or in java:
String race = getResources().getText(R.string.race_orc);