我尝试创建一个Firebase测验应用程序项目。它的工作很好,但是当我按下错误的按钮时,它挂起了,下一次无法使用。 我的代码在这里:
@Override
public void onClick(View v) {
mCountDown.cancel();
//still have question in list
if (index < totalQuestion) {
Button clickedButton = (Button) v;
if (clickedButton.getText().equals(Common.list_question.get(index).getCorrectAnswer())) {
score += 10;
correctAnwer++;
showQuestion(++index);
}
txtScore.setText(String.format("%d", score));
}
}
正确回答后,它将使用以下方法:
private void showQuestion(int index) {
if (index < totalQuestion) {
thisQuestion++;
txtQuestionNum.setText(String.format("%d / %d", thisQuestion, totalQuestion));
progressBar.setProgress(0);
progressValue = 0;
if (Common.list_question.get(index).getIsImageQuestion().equals("true")) {
Picasso.with(getBaseContext())
.load(Common.list_question.get(index).getQuestion())
.into(question_image);
question_image.setVisibility(View.VISIBLE);
question_text.setVisibility(View.INVISIBLE);
} else {
question_text.setText("Q. "+Common.list_question.get(index).getQuestion());
question_image.setVisibility(View.INVISIBLE);
question_text.setVisibility(View.VISIBLE);
}
btnA.setText(Common.list_question.get(index).getAnswerA());
btnB.setText(Common.list_question.get(index).getAnswerB());
btnC.setText(Common.list_question.get(index).getAnswerC());
btnD.setText(Common.list_question.get(index).getAnswerD());
mCountDown.start();
} else {
Intent intent = new Intent(this, Done.class);
Bundle dataSend = new Bundle();
dataSend.putInt("SCORE", score);
dataSend.putInt("TOTAL", totalQuestion);
dataSend.putInt("CORRECT", correctAnwer);
intent.putExtras(dataSend);
startActivity(intent);
finish();
}
}
但是在回答错误之后它不起作用。我需要为此设置条件,但不知道如何为 else 条件
编写代码答案 0 :(得分:1)
如果我理解正确,则此逻辑将检查用户是否单击了正确的答案按钮:
if (clickedButton.getText().equals(Common.list_question.get(index).getCorrectAnswer())) {
score += 10;
correctAnwer++;
showQuestion(++index);
}
现在,如果选择了正确答案(即进入score
语句),您只希望更改correctAnwer
和正确答案的数量(if
),但是您< em>总是想要显示下一个问题,无论答案是否正确。最简单的方法是将showQuestion
移到if
语句之外,如下所示:
if (clickedButton.getText().equals(Common.list_question.get(index).getCorrectAnswer())) {
score += 10;
correctAnwer++;
showQuestion(++index);
}
showQuestion(++index);
txtScore.setText(String.format("%d", score));
尽管如果您确实想在回答下一个问题之前对错误的答案执行其他操作,则可以像这样使用else
语句:
if (clickedButton.getText().equals(Common.list_question.get(index).getCorrectAnswer())) {
score += 10;
correctAnwer++;
showQuestion(++index);
} else {
// Do stuff that only needs to be done for an incorrect answer
showQuestion(++index);
}
txtScore.setText(String.format("%d", score));