从 string.xml 中随机选择一个文本
Choose a random text from string.xml
我有一个 string.xml 文件 text_1 ... text_100
现在我想从中选择一个随机文本并将其显示在 TextView 上。
我尝试使用
String text = "text_";
int randomNum = rand.nextInt((100 + 1) + 1;
text = text + String.valueOf(randomNum);
txt.setText(getString(R.string.text);
所以现在它不起作用,因为字符串文件中没有 "text"...
也许有一些建议?
你可以使用这个,但这是不好的做法:
public static int getResId(String resName, Class<?> c) {
try {
Field idField = c.getDeclaredField(resName);
return idField.getInt(idField);
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
你的情况:
getResId(text, String.class);
更好的选择是在 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>
然后:
String[] planets = res.getStringArray(R.array.planets_array);
int randomNum = rand.nextInt(planets.size() - 1);
txt.setText(planets[randomNum]);
你不只是想出这样的 int id。由于您知道资源名称,因此使用 Resources.class
的这种方法:getIdentifier(resIdName, resTypeName, packageName)
由于资源属于上下文,您可以:
String text = "text_";
int randomNum = rand.nextInt((100 + 1) + 1;
text = text + String.valueOf(randomNum);
int textId = getResources().getIdentifier(text, "string", getPackageName());
txt.setText(getString(textId));
你的字符串资源中有项目的资源 ID。
It was answered here
我有一个 string.xml 文件 text_1 ... text_100 现在我想从中选择一个随机文本并将其显示在 TextView 上。 我尝试使用
String text = "text_";
int randomNum = rand.nextInt((100 + 1) + 1;
text = text + String.valueOf(randomNum);
txt.setText(getString(R.string.text);
所以现在它不起作用,因为字符串文件中没有 "text"...
也许有一些建议?
你可以使用这个,但这是不好的做法:
public static int getResId(String resName, Class<?> c) {
try {
Field idField = c.getDeclaredField(resName);
return idField.getInt(idField);
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
你的情况:
getResId(text, String.class);
更好的选择是在 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>
然后:
String[] planets = res.getStringArray(R.array.planets_array);
int randomNum = rand.nextInt(planets.size() - 1);
txt.setText(planets[randomNum]);
你不只是想出这样的 int id。由于您知道资源名称,因此使用 Resources.class
的这种方法:getIdentifier(resIdName, resTypeName, packageName)
由于资源属于上下文,您可以:
String text = "text_";
int randomNum = rand.nextInt((100 + 1) + 1;
text = text + String.valueOf(randomNum);
int textId = getResources().getIdentifier(text, "string", getPackageName());
txt.setText(getString(textId));
你的字符串资源中有项目的资源 ID。
It was answered here