If a radio button is already clicked in Android, how can I prevent it from being clicked again?
Mahak Singhvi
RadioButton
I want to stop the second click if someone has already clicked on a RadioButton
in the RadioGroup
. If someone clicks 2 times, the user will not be able to change the selected click. I'm trying to use a to prevent this, boolean
but it doesn't work. Where am I going wrong?
Here is my code:
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// checkedId is the RadioButton selected
rb = (RadioButton) findViewById(checkedId);
user_radio_answer = (String) rb.getText();
rb.setOnClickListener(new View.OnClickListener() {
private boolean isChecked = true;
@Override
public void onClick(View v) {
if (isChecked) {
if (rb.isChecked() ) {
isChecked = false;
}
}
if (correct_answer1.equals(user_radio_answer)) {
rb.setBackgroundColor(Color.GREEN);
// Toast.makeText(getApplicationContext(), "Correct ☺ : " + user_radio_answer, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Incorrect Answer :( ..Correct Answer : " + correct_answer1, Toast.LENGTH_LONG).show();
rb.setBackgroundColor(Color.parseColor("#FF5733"));
answer1 = rb_answer1.getText().toString();
answer2 = rb_answer2.getText().toString();
answer3 = rb_answer3.getText().toString();
answer4 = rb_answer4.getText().toString();
if (answer1.equals(correct_answer1)) {
rb_answer1.setBackgroundColor(Color.GREEN);
}
if (answer2.equals(correct_answer1)) {
rb_answer2.setBackgroundColor(Color.GREEN);
}
if (answer3.equals(correct_answer1)) {
rb_answer3.setBackgroundColor(Color.GREEN);
}
if (answer4.equals(correct_answer1)) {
rb_answer4.setBackgroundColor(Color.GREEN);
}
}
new RadioHttpAsyncTask().execute("http:xxxxxx-xxxxxxxxxx-xxxxxxxx");
}
});
}
});
Rainmaker:
You can add two methods and call them when needed. You can add a condition that disables the group if the radio button is checked, and sets it to enabled if it is unchecked. The button can also be set to enable when clearing a radio group.
public void disableRG() {
for(int i = 0; i < radioGroup.getChildCount(); i++){
((RadioButton)radioGroup.getChildAt(i)).setEnabled(false);
}
}
public void enableRG() {
for(int i = 0; i < radioGroup.getChildCount(); i++){
((RadioButton)radioGroup.getChildAt(i)).setEnabled(true);
}
}