Android studio – Change string in textView

Tags: ,



I have some stings in the styles/string.xml as below:

<string name="string1">something</string>
<string name="string2">some other thisn</string>
<string name="string3">asdfgh jkl</string>
<string name="string4">qwerty uiop</string>
.
.
.

and I have a textView and a button in my current activity. When I click the button, the text in the textView has to change (to the next sting) according to what is currently shown. That is, if the current text in textView is string1, then it should change to string2.

The code below doesn’t work but will illustrate what I am looking for

count = 0;
public void onClick(View v) {
                count++;
                str="R.string.string" + count;
                textView.setText(str);
            }

I have to somehow convert the string to the actual value of (say)R.string.string1. Is there a way to do that? Or is there any other method to achieve what I am looking for?

Answer

You can create a string array resource similar to this one below:

<resources>
    <string-array name="my_string_array">
        <item>stringa</item>
        <item>stringb</item>
        <item>another string</item>
        <item>yet another string</item>
    </string-array>
</resources>
  // you can use a string array resource
  String[] strings = getResources().getStringArray(R.array.my_string_array)
  int count = 0;
  void onClick(View v) {
    if (count < strings.length)
       textView.setText(strings[count])
       count++;
  }


Source: stackoverflow