来自资源 Android 的随机数组

Random array from resource Android

如何使用以下 xml 从资源文件中获取 java 中的随机问题:

<array name="question1">
    <item name="id">1</item>
    <item name="question">Question 1?</item>
    <item>@array/possible_answers1</item>
    <item name="correct_answer">1</item>
</array>
    <string-array name="possible_answers1">
        <item>Answer1</item>
        <item>Answer2</item>
        <item>Answer3</item>
        <item>Answer4</item>
    </string-array>

<array name="question2">
    <item name="id">2</item>
    <item name="question">Question 2?</item>
    <item>@array/possible_answers2</item>
    <item name="correct_answer">3</item>
</array>
    <string-array name="possible_answers2">
        <item>Answer1</item>
        <item>Answer2</item>
        <item>Answer3</item>
        <item>Answer4</item>
    </string-array>

为了得到 java 中的第一个问题,我使用:

String[] str_quest = res.getStringArray(R.array.question1);
str_question = str_quest[1];

但是我怎样才能得到随机问题呢? 感谢阅读!

这会起作用:

Random rand = new Random();
int numberOfQuestion = 3;//For example
int randomQuestionID = this.getResources().getIdentifier("question"+rand.nextInt(numberOfQuestion), "array", this.getPackageName());
str_question = res.getStringArray(randomQuestionID)[1];

为问题数组的所有 id 创建一个整数数组:

int[] question_arr=new {R.array.question1,R.array.question2,...};
Random randnum = new Random();

从 question_arr 获取随机数组 ID:

int question_index=question_arr[randnum.nextInt(question_arr.length)];
String[] str_quest = res.getStringArray(question_index);