Difficulty in accessing a SwitchCompat from the Nav Drawer

Viewed 595

I have a navigation drawer in my application that I figured could benefit from a toggle switch, shown here:

Staffpad Toggle

My problem is that I can't actually access whether or not the switch has been toggled.

activity_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/piano"
            app:actionLayout="@layout/action_view_switch"
            android:title="Piano Mode" />

action_view_switch.xml

<?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/piano_switch"
        />
</LinearLayout>

And here's the code snippet where I try to access the switch, but the onCheckedChanged listener never activates:

 View v = getLayoutInflater().inflate(R.layout.action_view_switch, null);
        SwitchCompat piano = (SwitchCompat) v.findViewById(R.id.piano_switch);

        piano.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Settings.piano = isChecked;
                Log.d("Switch", "You a-toggled mah switch");
            }
        });
2 Answers

For some people like me, the below answer will be helpful

navigationView = (NavigationView) findViewById(R.id.navigation_view); //Here you should enter your navigation view id

First, get the id of item in the navigation bar (R.id.piano) then get id of Switch (R.id.piano_switch)

SwitchCompat piano = (SwitchCompat) navigationView.getMenu().findItem(R.id.piano).getActionView().findViewById(R.id.piano_switch);
piano.setOnCheckedChangeListener.......

Now the order of items in the Navigation bar does not matters.

Related