Switch in Navigation drawer item with Design Support Library on Android
Your menu item for the navigation drawer:
<item
android:id="@+id/nav_item1"
android:icon="@drawable/ic_item1"
android:title="item1"
app:actionLayout="@layout/layout_switch"
/>
and the layout for that item:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.SwitchCompat
android:id="@+id/drawer_switch"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:text=""/>
</LinearLayout>
EDIT:
I ended up using a different approach. In fact, I found out that you can use any view in the drawer, so there's no point in bothering with the menu stuff. Just create a view the usual way (with listeners, etc.) and add in to the drawer.
One way I have found of doing this would be to use setActionView on the menuItem you want:
mNavigationView.getMenu().findItem(R.id.nav_connect)
.setActionView(new Switch(this));
// To set whether switch is on/off use:
((Switch) mNavigationView.getMenu().findItem(R.id.nav_connect).getActionView()).setChecked(true);
Probably want a click listener as well to change the state of the Switch:
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.nav_connect:
((Switch) menuItem.getActionView()).toggle();
return true;
}
}
}
I haven't tried, but you could probably use android:actionLayout="@layout/switch_layout" in xml and point to a custom layout you created.
Also could try using an ActionProvider which might offer a little more robustness. I haven't tried this method either though.