Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unknown attribute onItemSelected/onCheckedChanged

I created SwitchCompat and added android:onCheckedChanged. everything works fine, but Android Studio marks this attribute as warning with description.

Unknown attribute android:onCheckedChanged.

The same case is with AppCompatSpinner with android:onItemSelected.

Why Android Studio displaying this warning? My Android Studio version is 3.5.1

screenshot with warning

like image 625
AndroidBoy Avatar asked Jul 06 '26 06:07

AndroidBoy


1 Answers

That is because SwitchCompat actually does not have such attribute (see documentation), so you can't assign the listener in the XML. Try implementing an onClickListener instead or assign the OnCheckedChanged listener outside of XML, such as:

  final SwitchCompat switchButton = (SwitchCompat) view.findViewById(R.id.switch_button);
  switchButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
      //do stuff
    }
  });

Edit: You can also get the switch button from the dataBinding object in java code by calling binding.switch_button which returns the SwitchButton directly.

like image 116
Jan Málek Avatar answered Jul 09 '26 09:07

Jan Málek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!