我目前正在开发Android 测验应用,我实现了“重置”按钮,可以重置问题并将其随机化,但我在调用随机字符串时遇到问题。 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个并在屏幕上显示。 问题是,如果我想使用randomizer生成的整数在.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.
}
如何让计算机区分String的名称?所以它显示真实的问题,而不是“q1”“q6”“q17”?
提前感谢您的帮助!
答案 0 :(得分:0)
您可以使用getIdentifier()实用程序从string.xml文件访问字符串。
private String getStringByName(String name) {
int resId = getResources().getIdentifier(name, "string", getPackageName());
return getString(resId);
}
如果您还完全尝试了另一种方法并创建一个看起来像这样的问题类,那将会容易得多:
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;
...
}
}
而且,create和ArrayList = new ArrayList&lt;&gt;();并用你的问题填充它。然后,您可以通过数组中的ID /位置访问它们,按名称搜索它们等等。将来,您可以使用此模型从服务器请求问题列表。
答案 1 :(得分:0)
question.setText("q" + randomQuestion);
在此处,您传递"q"
后,您的参数会被推断为字符串,因此它会按预期显示"q-randomNumber"
。我想你想要的是将实际ID传递给setText
。为此,您可以采用与使用&#34; string&#34;查找问题textview ID相同的方法。而不是&#34; id&#34;。
答案 2 :(得分:0)
在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;