我在 strings.xml 中有三个字符串:
<string name="book_1">Tom Sawyer</string>
<string name="book_2">Huck Finn</string>
<string name="book_3">Roughing It</string>
我知道我可以通过显式选择一个字符串来引用 java 中的字符串:
String book = R.string.book_1;
如果我有 int x 存储书号,我如何引用字符串 book_x?
更新和解决方案: 我明白了我在寻找什么。这是我的第一个 Stackoverflow 问题,我应该提供更多背景信息。我保证我会在这方面做得更好。感谢所有回复的人。
// Getting book title. Displaying the book title in the TextView
// int booknumber is already defined
TextView tv = (TextView) findViewById(R.id.booktitle_textview);
String bookName = "book_" + Integer.toString(booknumber);
int resourceId = getResources().getIdentifier(bookName, "string", "com.example.mypackage");
tv.setText(getString(resourceId));
最佳答案
将三个字符串放入一个数组中:
String[] strs = {R.string.book_1, R.string.book_2, R.string.book_3};
然后使用strs[x - 1]
访问适当的元素。
关于java - Android:构建字符串引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43837477/