[英]Android Get switch from ActionLayout on Navigation Drawer
如何从我的actionLayout(这是一个菜单项)中具体获取开关,以便设置“ setOnCheckedChangeListener”事件?
这是我的导航抽屉菜单:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="@+id/nav_switch"
app:actionLayout="@layout/action_view_switch"
android:title="One-to-one mode" />
</menu>
使用action_view_switch actionlayout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<Switch
android:id="@+id/otoSwitch"
android:layout_width="fill_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
最后,我的导航抽屉:
<android.support.design.widget.NavigationView
android:id="@+id/nvView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="@android:color/white"
app:menu="@menu/drawer_view"
app:headerLayout="@layout/nav_header"/>
我了解我可以执行以下操作:
Menu menu = navigationView.getMenu();
MenuItem menuItem = menu.findItem(R.id.nav_switch);
View actionView = MenuItemCompat.getActionView(menuItem);
actionView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
但这并没有给我任何像isChecked这样的状态,例如'setOnCheckedChangeListener'。 如何获取切换视图,以便可以设置其侦听器?
您几乎已经弄清楚了,还有几件事。 这是对我有用的东西!
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<Switch
android:id="@+id/otoSwitch"
android:layout_width="fill_parent"
android:layout_height="match_parent"
/>
接下来,从菜单项中获取视图。
Menu menu = navigationView.getMenu();
SwitchCompat actionView = (SwitchCompat) menu.findItem(R.id.nav_switch).getActionView().findViewById(R.id.ontoSwitch);
actionView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
我在getActionView之后还有另一个findViewById的原因是,因为getActionView将返回LinearLayout视图,并且我们的开关位于LinearLayout内,所以我们只从返回给我们的当前LinearLayout中查找视图ID,从而找到了findItem(R.id.nav_switch)。 getActionView()。findView ...希望这会有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.