java - 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);
}
解决方案
您不必在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!
推荐阅读
- jquery - 如何在 javascript 中识别 toastr 以供以后使用
- android - 什么时候应该在 Flutter 中使用 BLoC 模式?
- macos - conf.ps 在哪里以及是什么?当我输入命令 ps 时询问
- python - Flask API 无法从 PHP 接收数据
- sql - 合并没有视图的子查询
- php - PHP将字符串转换为变量不起作用
- c - 在 Mac OS Catalina 10.15.2 上安装 Library X11
- f# - 具有多个函数的递归 F#
- windows - 来自 docker-compose 的环境变量未传递给容器
- python - 如何在 add_widget() 中引用 id