I am working on quiz app for Android and I use RadioButtons in RadioGroup. I want to achieve that when someone checks the right answer (this case its id/krzyzyk
) the score will increase by one point. I made this code:
int score = 2;
public void onRadioButtonClicked(View view) {
RadioButton radiobutton1 = (RadioButton) findViewById(R.id.krzyzyk);
if (radiobutton1.isChecked()) {
score = score + 1;
}
}
It works but when I run the app and click in another RadioButton and again id/krzyzyk
the score will update again. Can you help me to fix this problem?
Your code will always increment the score when the user taps on the RadioButton krzyzyk
.
I'll suggest you to Submit the answer and go to the next question incrementing the score if the selected RadioButton is correct.
Change your code to something like:
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.correct_answer: // this is id/krzyzyk
if (checked)
score++;
// Go to next question
break;
case R.id.wrong_answer:
if (checked)
// Go to next question.
break;
}
}