简体   繁体   中英

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM