I want to create a NavigationView with checkbox or switch , I just want to have this feature in my navigation to items switch and it should work just like this : When I turn one switch to another it changes to off state. What I did to have a switch is, this :
<?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:layout_width="fill_parent"
android:layout_height="match_parent"
android:id="@+id/switchs"
/>
</LinearLayout>
<?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">
<group android:checkableBehavior="single">
<item
android:id="@+id/nav_menu1"
android:icon="@mipmap/ic_launcher"
android:title="Menu 1" />
<item
android:id="@+id/nav_menu2"
android:icon="@mipmap/ic_launcher"
android:title="Menu 2" />
<item
android:id="@+id/nav_menu3"
app:actionLayout="@layout/action_view_switch"
android:icon="@mipmap/ic_launcher"
android:title="Menu 3" />
<item
android:id="@+id/nav_menu4"
app:actionLayout="@layout/action_view_switch"
android:icon="@mipmap/ic_launcher"
android:title="Menu 4" />
</group>
</menu>
But I can not have a value or status a switch and have a listener to see a change status
first of all create a layout action_view_checkbox.xml as below
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:layout_centerVertical="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toLeftOf="@+id/checkbox" />
<android.support.v7.widget.AppCompatCheckBox
android:id="@+id/checkbox"
android:layout_centerVertical="true"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:text="" />
</RelativeLayout>
and add layout as an item to the menu
<menu xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/check_box_menu"
app:actionLayout="@layout/action_view_checkbox"
android:title="Title" />
</menu>
And check click event as
Menu menu = navigationView.getMenu();
MenuItem menuItem = menu.findItem(R.id.check_box_menu);
View actionView = MenuItemCompat.getActionView(menuItem);
actionView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});