您好我正在创建一个测验应用程序。我想在我的提交按钮中添加一个功能,如果用户没有在radiobutton中选择任何答案,将会有一条消息说“请选择答案”这是代码
public void onClickNext(View view) {
String level = getIntent().getExtras().getString("level");
DbHelper db = new DbHelper(this);
db.getQuestByLevel(level, qnum);
RadioGroup grp = (RadioGroup) findViewById(R.id.questionAndAnswers);
RadioButton answer = (RadioButton) findViewById(grp.getCheckedRadioButtonId());
if (corAnswer != null && corAnswer.equalsIgnoreCase((String) answer.getText())) {
score++;
Log.d("answer", "Your score" + score);
}
if (qnum <= 5) {
}
else {
Intent intent = new Intent(QuizActivity.this, ResultActivity.class);
Bundle b = new Bundle();
b.putInt("score", score);
intent.putExtras(b);
startActivity(intent);
finish();
}
txtQuestion.setText(db.question);
rda.setText(db.optionA);
rdb.setText(db.optionB);
rdc.setText(db.optionC);
rdd.setText(db.optionD);
corAnswer = db.answer;
qnum++;
rdgrp.clearCheck();
}
}
答案 0 :(得分:0)
在以下一行
RadioButton answer = (RadioButton) findViewById(grp.getCheckedRadioButtonId());
如果未选中RadioButton
,getCheckedRadioButtonId()
将返回&#34; -1&#34;并且由于没有带有该ID的视图,&#34;回答&#34;将是null
。
所以你可以做以下
if (answer == null)
{
Toast.makeText(MyActivity.this, "select an answer please", Toast.LENGTH_SHORT).show();
// nothing more to do here so
return;
}
if (corAnswer!= null && corAnswer.equalsIgnoreCase((String) answer.getText())
{
// continue as before
}