4
我在我的应用程序,我想可能从一个拨动开关受益抽屉式导航访问SwitchCompat,如下所示:难度从导航抽屉
我的问题是,我不能实际上访问是否切换已被切换。
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");
}
});
感谢您的答复!不幸的是,这返回null,但我想通了:'SwitchCompat piano =(SwitchCompat)navigationView.getMenu().getItem(0).getActionView()。findViewById(R.id.piano_switch);'似乎加载正确,看起来很粗糙。不过再次感谢! –
这取决于你如何用XML来安排你的NavigationView。我只是指出了方式! 很高兴知道它有帮助:-) –
对,我发布后发现我没有给我完整的配置,但很高兴你知道反正。 –