gpt4 book ai didi

java - Android 从抽屉导航上的 ActionLayout 获取开关

转载 作者:行者123 更新时间:2023-11-29 07:33:27 30 4
gpt4 key购买 nike

我如何专门从我的 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 Action 布局:

<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) {

}
});

但这并没有给我任何状态,例如像“setOnCheckedChangeListener”那样的 isChecked。如何获取切换 View 以便设置其监听器?

最佳答案

你已经差不多明白了,只是还有一些事情。这对我有用!

<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"
/>

接下来从菜单项中获取 View 。

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 View ,而我们的开关在 LinearLayout 内部,所以我们只是从返回给我们的当前 LinearLayout 中找到 View ID,因此 findItem(R.id. nav_switch).getActionView().findView...希望这会有所帮助

关于java - Android 从抽屉导航上的 ActionLayout 获取开关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39043471/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com