Search code examples
androidbutterknife

How to bind to a combobox using butterknife?


Using Butterknife, how can I declare a method that is called when the combobox is selected or deselected? Using @OnItemSelected gives a ClassCastException:

java.lang.ClassCastException: androidx.appcompat.widget.AppCompatCheckBox 
                              cannot be cast to android.widget.AdapterView

Solution

  • UPDATE:

    It is better to use @OnCheckedChanged like this:

        @OnCheckedChanged(R.id.myCheckBox)
        void myCheckBoxSelected(boolean checked) {
            // use checked here
        }
    

    The advantage is that you immediately get the boolean flag.

    ORIGINAL ANSWER:

    You need to use the @OnClick annotation:

        @OnClick(R.id.myCheckBox)
        void myCheckBoxSelected(CheckBox checkBox) {
            boolean checked = checkBox.isChecked();
            // use checked here
        }
    

    Also make sure you use isChecked to know the checked state (Do not use isSelected() which also exists on a Combobox)