2016-03-24 210 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

對,我發佈後發現我沒有給我完整的配置,但很高興你知道反正。 –