WonUK JUNG WonUK JUNG - 1 month ago 17
Android Question

How can i set Listener to switch in Navigation drawer?

actvity_main_drawer.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">

<group android:checkableBehavior="single">
<item
android:id="@+id/nav1"
android:icon="@drawable/ic_lock_outline_black_24dp"
android:title="test1" />
<item
android:id="@+id/nav2"
android:icon="@drawable/ic_add_a_photo_black_24dp"
android:title="test2" />
<item
android:id="@+id/nav3"
android:icon="@drawable/ic_face_black_24dp"
android:title="test3" />

</group>




activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">

<include layout="@layout/content_main" />

<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"

app:headerLayout="@layout/nav_header_main"
app:menu="@menu/activity_main_drawer" />




onoff_toggle.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="horizontal"
android:layout_width="match_parent"
android:id="@+id/switch_layout"
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:checked="false"
android:textOff="off"
android:textOn="on"
app:showText="true"/>

</LinearLayout>


this is my switch in navigation drawer menu item xml code

how can i set Listener to switch

Answer

At the place where you prepare the Navigation view menu items try this.

NavigationView navigationView=(NavigationView)findViewById(id);

//get the menu from the navigation view
Menu menu=navigationView.getMenu();

//get switch view
SwitchCompat switchcompat=(SwitchCompat) MenuItemCompat.getActionView(menu.findItem(R.id.nav_notify)).findViewById(R.id.drawer_switch);

//add listener
switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    //your action
                }
            });