Search code examples
androidandroid-actionbarandroid-toolbarswitchcompat

Can't find reference to switch compat in custom layout in toolbar


I'm trying to add a switchcompat to the toolbar, the menu item references a custom layout

toolbar_switch.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_marginRight="8dp"
android:layout_height="match_parent">

<android.support.v7.widget.SwitchCompat
    android:layout_width="wrap_content"
    app:showText="false"
    android:id="@+id/switch_online"
    android:layout_centerInParent="true"
    android:layout_height="wrap_content" />

</RelativeLayout>

menu_main_activity.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">
<item
    android:id="@+id/menu_toggle"
    android:actionLayout="@layout/toolbar_switch"
    app:showAsAction="always"
    android:title="" />
</menu>

the menu inflates in the activity fine if i set the menu item to an image or text, but when I point it to a custom layout it doesn't show up

    setSupportActionBar(toolbar);
    actionBar = getSupportActionBar();
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    toolbar.setOnMenuItemClickListener(this);

    switchOnline = (SwitchCompat)toolbar.findViewById(R.id.switch_online);

and my app theme is bassed off of AppCompat


Solution

  • Since you're using a support action bar, you need to use app:actionLayout to specify your custom view.