Implementing switch in toolbar in android studio

  android-studio, button, checked

I am trying to implement switch button on the toolbar. It shows on the toolbar and turns on and off but there is no functions implemented when it is on or off. I have the switch button in the menu as follows

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_settings"
        android:title="Settings"
        app:showAsAction="never"/>
    <item
        android:id="@+id/switch_button"
        android:title="Switch"
        app:showAsAction="always"
        android:orderInCategory="3"
        app:actionViewClass="androidx.appcompat.widget.SwitchCompat" />
   
  
    <item android:id="@+id/edit"
        android:title="search_title"
        android:orderInCategory="1"
        android:icon="@drawable/edit"
        app:showAsAction="always|collapseActionView"
       />

</menu> 

and this is the java file

                   case R.id.action_settings:
                        Toast.makeText(getActivity(),"action settings clicked",Toast.LENGTH_SHORT).show();
                        break;
                   case R.id.switch_button:
                       SwitchCompat switch_state = (SwitchCompat) item.getActionView();
                       switch_state.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                           @Override
                             public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                           if (isChecked){
                               Toast.makeText(getActivity(),"action settings clicked",Toast.LENGTH_SHORT).show();
                           } else {
                               Toast.makeText(getActivity(),"action settings clicked",Toast.LENGTH_SHORT).show();

                           }
                       });

The action toast is showing for settings but the switch toast is not showing and there is no error in the logcat as well.

Source: Android Studio Questions

LEAVE A COMMENT