繁体   English   中英

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

[英]Java/Xml/Android - Calling random Strings from .XML String file in the Java

我目前正在开发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个问题,并将其显示在屏幕上。 问题是,如果我想使用随机化器生成的整数来在.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;
... 
}
}

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

question.setText("q" + randomQuestion);

在这里,因为您传递了"q" ,所以您的参数被推断为字符串,因此它将按预期显示"q-randomNumber" 我认为您想要的是将实际ID传递给setText 为此,您可以使用与使用“字符串”而不是“ id”查找问题textview 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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM