2016-03-24 179 views
4

我在我的应用程序,我想可能从一个拨动开关受益抽屉式导航访问SwitchCompat,如下所示:难度从导航抽屉

Staffpad Toggle

我的问题是,我不能实际上访问是否切换已被切换。

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> 

而这里的代码片段,我试图访问交换机,但onCheckedChanged听众从来没有激活:

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"); 
      } 
     }); 

回答

1

其实你正在创建一个新的视图,并设置检查更改监听器!

它不会将监听器设置在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"); 
      } 
     }); 
+2

感谢您的答复!不幸的是,这返回null,但我想通了:'SwitchCompat piano =(SwitchCompat)navigationView.getMenu().getItem(0).getActionView()。findViewById(R.id.piano_switch);'似乎加载正确,看起来很粗糙。不过再次感谢! –

+1

这取决于你如何用XML来安排你的NavigationView。我只是指出了方式! 很高兴知道它有帮助:-) –

+0

对,我发布后发现我没有给我完整的配置,但很高兴你知道反正。 –