我认为你应该做的最好的事情就是创建一个Question
类。
public class Question {
@DrawableRes
private int imageId;
private String[] answers;
private int correctAnswerIndex;
public Question(int imageId, int correctAnswerIndex, String... answers) {
this.imageId = imageId;
this.correctAnswerIndex = correctAnswerIndex;
this.answers = answers;
}
@DrawableRes
public int getImageId() { return imageId; }
public String[] getAnswers() { return answers; }
public int getCorrectAnswerIndex() { return correctAnswerIndex; }
}
该课程代表一个问题。它有
- 的
imageId
字段来存储问题
- 的图像的
answers
字段来存储所有可能的答案是,用户可以选择
- 一个
correctAnswerIndex
存储正确的答案。这实际上存储了answers
数组中正确答案的索引。假设您有{"blue", "red", "green", "yellow"}
作为answers
数组,并且正确的答案是blue
,您将设置正确答案索引为0
。
不明白如何使用它?我们来看一个例子。
此刻,你有一个图像id的数组。您应该将其更改为Question
s的数组。
private Question[] questions = new Question[4];
和你fillQuestion
方法是:
questions[0] = new Question(R.drawable.sweeper_is_handsome, 0, "True", "False", "Maybe", "I don't know");
questions[1] = new Question(R.drawable.no_one_can_beat_jon_skeet_in_reputation, 1, "True", "False", "Maybe", "I don't know");
// you get the idea.
正如你所看到的,在回答第一个问题是“真”(correctAnswerIndex
= 0),而第二个问题是“假“(correctAnswerIndex
= 1)。
现在你有一个数组充满了问题。你如何显示它?
我想你可以自己研究如何显示图像,所以让我们关注如何让按钮工作。
我猜你的按钮将在一个数组中,对吗?如果不是,那么你完全做错了。只需将四个按钮添加到数组中,这很简单。
您可以在每个按钮的点击处理程序上使用相同的功能。没关系。在点击监听器中,你有这样一个view
参数吧?
public void buttonOnClick(View view) {
// ⬆︎
// here
}
如果你正在做这个权利,view
应该是你的按钮数组中的项目。您可以使用indexOf
方法获取数组中按钮的索引。如果该索引匹配问题的correctAnswerIndex
,则用户选择了正确的答案!
但是,您如何知道显示哪个问题?您在您的活动课程中创建一个名为questionIndex
的变量来跟踪它!它应该从0开始,每当你显示一个新问题时,你就增加它!
编辑:
这是怎么您的单击处理按钮看起来像:
int pressedButtonIndex = btns.indexOf(view);
int correctAnswerIndex = questions[questionIndex].getCorrectAnswerIndex();
if (pressedButtonIndex == correctAnswerIndex) {
// This means the user chose the correct answer
if (questionIndex == 4) {
// This is actually the last question! No need to display the next!
return;
}
// load next question
questionIndex++;
someImageView.setImage(questions[questionIndex].getImageId());
for (int i = 0 ; i < 4 ; i++) {
btns[i].setText(questions[questionIndex].getAnswers()[i]);
}
// YAY! The next question is displayed.
} else {
// User chose the wrong answer, do whatever you want here.
}
是你的图像中的问题?并为您的问题,你会有正确的答案选项? –
我的问题是图像是的,好吧,而我有一个图像为每个问题和下面的标题。正确的答案将出现在按钮上,例如它可能像“这是什么颜色”,然后按下“蓝色”按钮,然后因为你知道它正确,它应该加载下一个图像和答案集。 – flanelman