Search code examples
androidandroid-actionbarandroid-switchandroid-togglebutton

Switch button not showing up in ActionBar?


I have a Switch that I placed into my ActionBar, but it doesn't seem to show up and I don't see why. This was my attempt:

create_post_menu.xml

<?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"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".CreatePost">

    <item
        android:id="@+id/toggle_test"
        android:title=""
        app:showAsAction="ifRoom"
        android:orderInCategory="1"
        android:actionViewClass="android.widget.Switch" />

    <item
        android:id="@+id/send_post"
        android:orderInCategory="2"
        android:title="Send"
        app:showAsAction="ifRoom" />

</menu>

CreatePost.java

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.create_post_menu, menu);
    // Get the action view used in your toggleservice item
    final MenuItem toggleservice = menu.findItem(R.id.toggle_test);
    final Switch actionView = (Switch) toggleservice.getActionView();
    actionView.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            // Start or stop your Service
        }
    });
    return super.onCreateOptionsMenu(menu);
}

I tried to instantiate the Switch to see if I can set a listener to see if you click on or off for the switch but I can't seem to instantiate it as I get an error trying to create the actionView variable in CreatePost.java. Can anyone help me with this? Thanks!


Solution

  • your are getting error because your actionView is null. change your Switch menu code

    <item
         android:id="@+id/toggle_test"
         android:title=""
         app:showAsAction="ifRoom"
         android:orderInCategory="1"
         android:actionViewClass="android.widget.Switch" /> 
    

    to app:actionViewClass="android.widget.Switch" look carefully it would be app not android like this...

    <item
          android:id="@+id/toggle_test"
          android:title=""
          app:showAsAction="ifRoom"
          android:orderInCategory="1"
          app:actionViewClass="android.widget.Switch" /> 
    

    and now change your java code like this

    final MenuItem toggleservice = menu.findItem(R.id.toggle_test);
    Switch actionView=(Switch) MenuItemCompat.getActionView(toggleservice );
    actionView.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            // Start or stop your Service
        }
    });