I have created programmatically 4 radio groups with 4 radio buttons. Each radio button represents an answer to a question. Let's say that we have in the first radio group, 3 wrong answers and only one correct answer. The first, the second and the third are wrong and the fourth is correct. When someone checks only one radio button, let say for example the first one, which is a wrong one, this goes to the wrongAnswersRadios
array list. But if someone checks the first one and then is changing his mind and checks the last one (the correct one) than the first one that was checked goes to wrongAnswersRadios
array list and the last one that was checked, goes to correctAnswerRadios array list. I think onClick
fires every time a radio button is checked.
How do i manage to add in the array lists only the last checked radio button from each radio group? Here is my code:
correctAnswerRadios = new ArrayList<>();
wrongAnswersRadios = new ArrayList<>();
radioGroup.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
for (int j = 0; j < 4; j++) {
checkedRadioButton[j] = ((RadioButton) v);
if (checkedRadioButton[j].isChecked() & CorrectAnswer == 1) {
correctAnswerRadios.add(checkedRadioButton[j]);
} else {
wrongAnswersRadios.add(checkedRadioButton[j]);
}
}
}
});
You can do something like this:
correctAnswerRadios = new ArrayList<>();
wrongAnswersRadios = new ArrayList<>();
radioGroup.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
for (int j = 0; j < checkedRadioButton.length; j++) {
correctAnswerRadios.remove(checkedRadioButton[j]);
wrongAnswersRadios.remove(checkedRadioButton[j]);
}
for (int j = 0; j < checkedRadioButton.length; j++) {
if (checkedRadioButton[j].isChecked() & CorrectAnswer == 1) {
correctAnswerRadios.add(checkedRadioButton[j]);
} else {
wrongAnswersRadios.add(checkedRadioButton[j]);
}
}
}
});