来自资源Android的随机数组

时间:2015-01-06 02:34:45

标签: java android arrays xml

如何使用以下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];

但我怎么能得到随机问题? 谢谢你的阅读!

2 个答案:

答案 0 :(得分:0)

这将有效:

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];

答案 1 :(得分:0)

创建一个包含所有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);