首页 > 解决方案 > Java / Android 循环 - 随机数据分配给 Android SDK 中的按钮

问题描述

我正在为 Android 构建一个测验应用程序的变体(所以在 Java 中)。我有测验问题和四个测验答案 A、B、C 和 D 的列表。

我想随机化可能的答案(A、B、C 和 D),这样如果用户多次遇到相同的问题,他们不一定会以相同的顺序看到答案选项。

下面的代码通过随机化顺序来工作(例如到 DACB)。然后它查找 A 并将其分配给四个按钮之一,具体取决于它在数组中的位置(在本例中,它位于第二个位置,因此它被分配给按钮 B)。对 B、C 和 D 重复相同的方法。这很有效,但不是特别优雅或高效。一定有更简洁的方法...?

ArrayList<String>  mylist = new ArrayList<String>();
mylist.add("A");
mylist.add("B");
mylist.add("C");
mylist.add("D");
Collections.shuffle(mylist);
final int index=Ints.indexOf(mylist, "A");
if (index==0) {
    button1 = findViewById(R.id.buttonA);
} else if (index==1){
    button1 = findViewById(R.id.buttonB);
} else if (index==2){
    button1 = findViewById(R.id.buttonC);
} else if (index==3){
    button1 = findViewById(R.id.buttonD);
}

final int index=Ints.indexOf(mylist, "B");
if (index==0) {
    button2 = findViewById(R.id.buttonA);
} else if (index==1){
    button2 = findViewById(R.id.buttonB);
} else if (index==2){
    button2 = findViewById(R.id.buttonC); 
} else if (index==3){
    button2 = findViewById(R.id.buttonD);
}

final int index=Ints.indexOf(mylist, "C");
if (index==0) {
    button3 = findViewById(R.id.buttonA);
} else if (index==1){
    button3 = findViewById(R.id.buttonB);
} else if (index==2){
    button3 = findViewById(R.id.buttonC); 
} else if (index==3){
    button3 = findViewById(R.id.buttonD);
}

final int index=Ints.indexOf(mylist, "D");
if (index==0) {
    button4 = findViewById(R.id.buttonA);
} else if (index==1){
    button4 = findViewById(R.id.buttonB);
} else if (index==2){
    button4 = findViewById(R.id.buttonC); 
} else if (index==3){
    button4 = findViewById(R.id.buttonD);
}

标签: javaandroidloops

解决方案


您不必在findViewById每次需要为其设置文本时都获取按钮。它的效率较低。将您的按钮收集到ArrayList其中,以便它们按照所需的顺序(A、B、C、D),buttons例如调用。然后根据您的答案索引获取所需的按钮。

Collections.shuffle(mylist);

ArrayList<Button> buttons = new ArrayList<Button>();
buttons.add(findViewById(R.id.buttonA));
buttons.add(findViewById(R.id.buttonB));
buttons.add(findViewById(R.id.buttonC));
buttons.add(findViewById(R.id.buttonD));

final int index=Ints.indexOf(mylist, "A");
button1 = buttons.get(index)

// Do the rest!

推荐阅读