Using @OnCheckedChanged (ButterKnife) with radioGroup gives error in android

Niki picture Niki · May 9, 2017 · Viewed 19.6k times · Source

i recently integrated butterknife in my android project, and now i am trying to use @OnCheckedChanged annotation for radiogroup. but getting error of not giving callback. So what is the right method to call and get checkedId or this one is for radiobutton only and not for radiogroup.

@OnCheckedChanged(R.id.gendergroupid)
void onGenderSelected(RadioGroup group, int checkedId){
    switch(checkedId){
        case R.id.maleid:
            maleid.setEnabled(true);
            maleid.setChecked(true);
            break;
        case R.id.femaleid:
            femaleid.setEnabled(true);
            femaleid.setChecked(true);
            break;
        case R.id.bothid:
            bothid.setEnabled(true);
            bothid.setChecked(true);
            break;
    }
}

Gives me error

BloError:(89, 10) error: Unable to match @OnCheckedChanged method arguments.

Parameter #1: android.widget.RadioGroup did not match any listener parameters

Parameter #2: int did not match any listener parameters

Methods may have up to 2 parameter(s):

android.widget.CompoundButton boolean

These may be listed in any order but will be searched for from top to bottom.ckquote

Answer

Luiz Fernando Salvaterra picture Luiz Fernando Salvaterra · May 9, 2017

According the specification, this annotation needs to be used with 2 parameters, a CompoundButton and a boolean, so if you really want to use this listener, you have to change it like this:

@OnCheckedChanged(R.id.gendergroupid)
void onGenderSelected(CompoundButton button, boolean checked) {
   //do your stuff.
}

I think in your case this listener doesn't work, so you can use another implementation like:

@OnClick({R.id.radio_1, R.id.radio_2}) 
public void onRadioButtonClicked(RadioButton radioButton) {
    // Is the button now checked?
    boolean checked = radioButton.isChecked();

    // Check which radio button was clicked
    switch (radioButton.getId()) {
      case R.id.radio_1:
        if (checked) {
          // 1 clicked
        }
        break;
      case R.id.radio_2:
        if (checked) {
          // 2 clicked
        }
        break;
    }
}