迭代通过字符串存储在strings.xml中
问题描述:
这是我strings.xml
样本:迭代通过字符串存储在strings.xml中
<string name="intro_text_0">Hello </string>
<string name="intro_text_1">World </string>
<string name="intro_text_2">! </string>
.....
而且我有一个EditText
场,我要在继承中显示这些字符串当用户按下一个按钮。我想要做的是获得一个数组中的字符串,并在用户点击按钮时通过它们。首先,我需要真正找到我需要显示的字符串...
private String introTextToShow [] = new String[textLength];
for (int i=0; i<textLength; i++)
{
// ADD the intro_string_i to the array!
introTextToShow[i] = getString(R.string."intro_text_i"); // Oops
}
我虽然第一次使用的toString()追加对文本的其余部分i
但这并不工作。我如何迭代字符串而不直接在R.string.intro_text_0
中输入他们的名字?
答
我的第一个建议是,你作为tring array resource而非单个字符串资源的集合,使用:
<string-array name="intro_text">
<item>Hello </item>
<item>World </item>
<item>! </item>
</string-array>
,并在代码:
private String introTextToShow [];
public void onCreate(@Nullable Bundle savedInstanceState) {
introTextToShow = getResources().getStringArray(R.array.intro_text);
}
如果你需要保持介绍文字阵列作为其他原因的单个字符串资源,您可以按如下方式在循环中检索它们:
Resources res = getResources();
String pkg = getPackageName();
for (int i=0; i<textLength; i++) {
int resId = res.getIdentifier("intro_text_" + i, "string", pkg);
introTextToShow[i] = res.getString(resId);
}
https://*.com/questions/5904554/optimal-way-to-iterate-through-a-list-of-string-resources https://*.com/q/19799224/115145 – CommonsWare
任何你没有理由的原因使用'''资源而不是一堆单独的''资源吗? –
嗯,我不知道你可以存储字符串数组以及XML。这将做,谢谢。 –