2

I am using Android studio and have an array in my string.xml file as:

<string-array name="my_array">
    <item>text1</item>
    <item>text2</item>
    <item>text3</item>
</string-array>

I know how to access the array (and get the 1st item) in my MainActivity.java file:

myButton.setText(getResources().getStringArray(R.array.my_array)[0]);

My question: Is there anyway to set the text directly in the activity_main.xml file? I tried:

<Button
    android:id="@+id/myButton"
    android:text="@array/my_array[0]"
    ... />

but that causes an error. Without the "[0]" it displays the 1st value (text1), but maybe that is just because of the button's size and it's not showing the rest - I can't get it to display other items (e.g., text2).

Is it possible to access one value of the array directly in the layout file? Thanks.

michael
  • 123
  • 3

1 Answers1

2

I found a good answer here: https://stackoverflow.com/a/4161645/933969

Basically you create named strings first (and use those where you would want mystrings[x]) and then create your array using references to those named strings:

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

<string-array name="system">
    <item>@string/earth</item>
    <item>@string/moon</item>
</string-array>
William T. Mallard
  • 1,562
  • 2
  • 25
  • 33
  • 1
    thanks - i had seen the first link (in the answer you referenced), but not the second. it works, and since it means one only has to type in the text once, will do – michael May 11 '20 at 18:13