如何自动访问字符串.xml?(安卓)



我在字符串中有一堆字符串.xml,字符串的所有 id/名称都有一个模式(e0,e1,e2,e3,e4...)我想显示我所依赖的 23 个字符串之一用户选择的号码。例如,如果用户选择数字 6,而不是我想显示字符串"e6"。如何在不使用超长 switch 语句的情况下做到这一点?

我正在使用IntelliJ Idea

感谢您的帮助,您的所有答案都有效并且很有用。

您可以使用字符串数组

http://developer.android.com/guide/topics/resources/string-resource.html#StringArray

例:

XML 文件保存在 res/values/strings.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="planets_array">
        <item>Mercury</item>
        <item>Venus</item>
        <item>Earth</item>
        <item>Mars</item>
    </string-array>
</resources>

此应用程序代码检索字符串数组:

Resources res = getResources();
String[] planets = res.getStringArray(R.array.planets_array);

离开迈克尔的例子,我会做这样的事情:

Int num; //the number the user chooses
TextView tv = (TextView) findViewById(R.id.textviewID);
tv.setText(planets[num - 1]); //arrays start at zero so you would have to subtract one to get the right string. And also so you dont reference a nonexistent variable in the array.

最新更新