Java 难以从导航抽屉访问SwitchCompat

Java 难以从导航抽屉访问SwitchCompat,java,android,Java,Android,我的应用程序中有一个导航抽屉,我认为它可以从切换开关中获益,如下所示: 我的问题是,无论开关是否被切换,我实际上都无法访问 活动\u main\u 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-a

我的应用程序中有一个导航抽屉,我认为它可以从切换开关中获益,如下所示:

我的问题是,无论开关是否被切换,我实际上都无法访问

活动\u main\u 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" />
<?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>

实际上,您正在创建一个新视图,并将checked change listener设置为该视图

它不是将侦听器设置为NavDrawer中的开关,而是设置为新开关

您应通过以下方式访问NavDrawer中的交换机:

navigationView = (NavigationView) findViewById(R.id.navigation_view); //Here you should enter your navigation view id
SwitchCompat piano = (SwitchCompat)
navigationView.getMenu().findItem(R.id.piano_switch); // But this depends on how you made your view in XML. It may be navigationView.getMenu().getItem(0).findItem(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");
            }
        });

对于像我这样的一些人来说,下面的答案会很有帮助

navigationView = (NavigationView) findViewById(R.id.navigation_view); //Here you should enter your navigation view id
首先,在导航栏中获取项目id(R.id.piano),然后获取开关id(R.id.piano\u开关)


现在,导航栏中项目的顺序无关紧要。

谢谢您的回复!不幸的是,这会返回null,但我已经解决了:
SwitchCompat piano=(SwitchCompat)navigationView.getMenu().getItem(0.getActionView().findViewById(R.id.piano_开关)似乎正确加载了它,尽管看起来很粗糙。不过,再次感谢你!这取决于您如何在XML中安排NavigationView。我只是指了指路!很高兴知道它有帮助:-)是的,我在发帖后意识到我没有给出完整的配置,但很高兴你知道了。
navigationView = (NavigationView) findViewById(R.id.navigation_view); //Here you should enter your navigation view id
SwitchCompat piano = (SwitchCompat) navigationView.getMenu().findItem(R.id.piano).getActionView().findViewById(R.id.piano_switch);
piano.setOnCheckedChangeListener.......