嗨,我正在创建一个测试应用程序。我想在我的提交按钮中添加一个函数,如果用户没有在无线电按钮中选择任何答案,就会有一条消息:“请选择一个答案”,这是代码
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();
}}
发布于 2016-01-19 15:36:09
在下一行
RadioButton answer = (RadioButton) findViewById(grp.getCheckedRadioButtonId());如果没有选中RadioButton,getCheckedRadioButtonId()将返回"-1“,并且由于没有使用该id的视图,”应答“将是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
}https://stackoverflow.com/questions/34880290
复制相似问题