Java/Xml/Android - 从 Java 中的.XML字符串文件调用随机字符串



我目前正在开发安卓测验应用程序,我实现了"重置"按钮来重置问题并随机化它们,但我在从 MainActivity .java 中的文件中调用随机字符串时遇到问题.xml。

我把我所有的问题都列在 Strings.xml 文件中,以便于翻译:

<string name="q1">The reactor at the site of the Chernobyl nuclear disaster is now in which country?</string>
<string name="a1">A. Slovakia</string>
<string name="b1">B. Ukraine</string>
<string name="c1">C. Hungary</string>
<string name="d1">D. Russia</string>
<string name="q1answer">B</string>

所有的问题都列在该文件中,如q1,q2,q3,ABCD答案也是如此:a1,b1,c1,d1; a2,b2,c2,d2,等等

有很多问题,但按钮只选择其中的 5 个并将它们显示在屏幕上。问题是,如果我想使用随机发生器生成的整数来查找字符串,我就无法访问字符串.xml

for (int i = 1; i <= 5; i++) {
// I managed to get the identifier of the TextView with the for loop like that (TextViews for questios are listed q1q, q2q, q3q, q4q, q5q):
// I would like to do the same thing down there with Strings.
TextView question = (TextView) findViewById(getResources().getIdentifier("q" + i + "q", "id", this.getPackageName()));
// randomQuestion is the number of the question in random number generator from different method.
randomQuestion = randomizeNumbers();
// And here I'm stuck, this will show "q1-randomNumber" instead of the real question, 
// because it does not see it as an ID. I tried various different solutions, but nothing works.
question.setText("q" + randomQuestion);
// I left the most silly approach to show what I mean.
}

如何使计算机区分字符串的名称?所以它显示的是真正的问题而不是"q1"q6"q17"?

提前感谢您的帮助!

您可以使用 getIdentifier() 实用程序从 string.xml 文件中访问字符串。

private String getStringByName(String name) {
int resId = getResources().getIdentifier(name, "string", getPackageName());
return getString(resId);
}

如果您还完全尝试了另一种方法并创建一个看起来像这样的 Problem 类,那会容易得多:

public class Problem(){
int ID;
String question;
String answer1; String answer2; //..and so on
String answerCorrect;
public class Problem(int ID, String question, ...){
this.question= question;
... 
}
}

然后,创建 and ArrayList = new ArrayList<>(); 并用您的问题填充它。比,您将能够通过它们的 ID/在数组中的位置访问它们,按名称搜索它们等等。将来,您也可以使用此模型从服务器请求问题列表。

question.setText("q" + randomQuestion);

在这里,你的参数被推断为一个字符串,因为你传递了"q",所以它会按预期显示"q-randomNumber"。我认为您想要的是将实际ID传递给setText.为此,您可以采用与使用"字符串"而不是"id"查找问题文本视图 ID 相同的方法。

在 MainActivity 或函数中:

Resources res = getResources();
myString = res.getStringArray(R.array.YOURXMLFILE);
String q = myString[rgenerator.nextInt(myString.length)];
// WE GET THE TEXTVIEW
tv = (TextView) findViewById(R.id.textView15);
tv.setText(q);
// WE SET THE TEXTVIEW WITH A RANDOM QUESTION

并声明:

private String[] myString;
private static final Random rgenerator = new Random();
private TextView tv;

最新更新