我的应用程序中有一个导航抽屉,我认为可以从切换开关中受益,如下所示:
我的问题是,我无法实际访问交换机是否已被切换。
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");
}
});
答案 0 :(得分:1)
实际上,您正在创建一个新视图并将已选中的更改侦听器设置为该视图!
它没有在NavDrawer中设置Switch的监听器,而是设置一个新的开关!
您应该通过以下方式访问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");
}
});
答案 1 :(得分:0)
对于像我这样的人,下面的答案会有所帮助
navigationView = (NavigationView) findViewById(R.id.navigation_view); //Here you should enter your navigation view id
首先,在导航栏中获取项目ID(R.id.piano),然后获取Switch的ID(R.id.piano_switch)
SwitchCompat piano = (SwitchCompat) navigationView.getMenu().findItem(R.id.piano).getActionView().findViewById(R.id.piano_switch);
piano.setOnCheckedChangeListener.......
现在导航栏中的项目顺序无关紧要。