简体   繁体   English

单击后检查和取消选中RadioButton

[英]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. 当用户按下选中的单选按钮时,我将单选按钮设置为取消选中并清空textview。 Then, when the user pressed on the radio button again, I set it to checked and set some text in textview. 然后,当用户再次按下单选按钮时,我将其设置为选中状态并在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. 将其设置为false后,当我尝试再次检查它时,它将不起作用。 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. 相反,您可以在处理程序中检查该状态,然后进行适当响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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