QWERTY
QWERTY

Reputation: 2325

checking and unchecking a RadioButton upon clicking

I was having some problem when trying to check and uncheck radio button upon click.

What I am trying to do is, when the activity on load, the radio button is set to checked by default. When user pressed on the checked radio button, I set the radio button to uncheck and empty the textview. Then, when the user pressed on the radio button again, I set it to checked and set some text in textview. Here is my code:

@Click(R.id.radioButtonEmail)
void radioButtonEmailClicked(View v) {
    if(radioButtonEmail.isChecked() == true){
        radioButtonEmail.setChecked(false);
        editTextEmail.setText("");
    }else {
        radioButtonEmail.setChecked(true);
        editTextEmail.setText("TEST");
    }
}

However, this only worked for the first time when I tried to uncheck the radio button. After I set it to false, when I try to check it again, it does not work. Any ideas? Thanks!

Upvotes: 0

Views: 71

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522762

I don't have an exact explanation for the behavior you are seeing, but your logic looks off to me. I think you intend to do this:

@Click(R.id.radioButtonEmail)
void radioButtonEmailClicked(View v) {
    if (radioButtonEmail.isChecked()) {
        editTextEmail.setText("");
    }
    else {
        editTextEmail.setText("TEST");
    }
}

In other words, you don't manage whether the radio button is clicked from your event handler. Rather, you check for that state inside the handler, and then respond appropriately.

Upvotes: 2

Related Questions