Android Studio – 更改textView中的字符串

huangapple go评论77阅读模式
英文:

Android studio - Change string in textView

问题

我在 styles/string.xml 文件中有一些字符串,如下所示:

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

而且在我的当前活动中有一个 textView 和一个按钮。当我点击按钮时,textView 中的文本必须更改(变为下一个字符串),根据当前显示的内容。也就是说,如果 textView 中的当前文本是 string1,那么它应该更改为 string2

以下代码虽然不能正常工作,但可以说明我正在寻找的内容:

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

我必须以某种方式将字符串转换为实际的值(例如R.string.string1)。有没有办法做到这一点?或者有没有其他方法可以实现我所寻找的功能?

英文:

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?

答案1

得分: 4

你可以创建一个类似下面的字符串数组资源:

<resources>
    <string-array name="my_string_array">
        <item>stringa</item>
        <item>stringb</item>
        <item>另一个字符串</item>
        <item>仍另一个字符串</item>
    </string-array>
</resources>
// 你可以使用字符串数组资源
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++;
}
英文:

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++;
  }

huangapple
  • 本文由 发表于 2020年9月13日 05:51:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/63865246.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定