如何使用ViewBinding访问菜单中的开关?
menu/drawer_menu.xml:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:showIn="navigation_view"
>
<group android:checkableBehavior="single">
<item
android:id="@+id/nav_read"
android:title="@string/read"
android:icon="@drawable/ic_read"
/>
<item
android:id="@+id/nav_write"
android:icon="@drawable/ic_write"
android:title="@string/write"
/>
<item
android:id="@+id/nav_theme"
android:icon="@drawable/ic_theme"
android:title="Dark Theme"
app:actionLayout="@layout/theme_switch"
/>
</group>
<item android:title="@string/about">
<menu>
<item
android:id="@+id/nav_source_code"
android:icon="@drawable/ic_source_code"
android:title="@string/source_code"/>
</menu>
</item>
</menu>theme_switch.xml:
<androidx.appcompat.widget.SwitchCompat xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toggleSwitch"
android:layout_width="fill_parent"
android:layout_height="match_parent" />activity_home.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".HomeActivity"
android:id="@+id/drawer_layout"
android:fitsSystemWindows="true"
tools:openDrawer="start"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.appcompat.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/colorPrimary"
android:id="@+id/toolBar"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
/>
<FrameLayout
android:id="@+id/fl_home"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
<com.google.android.material.navigation.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:id="@+id/nav_view"
app:headerLayout="@layout/nav_header"
app:menu="@menu/drawer_menu"
/>
</androidx.drawerlayout.widget.DrawerLayout>这些是我的布局文件。
简而言之,我创建了一个DrawerLayout,并在其中使用NavigationView实现了我的菜单。其中一个菜单项是一个交换机,我想向该交换机添加一个.setOnCheckedChangeListener。
我尝试在我的activity的onCreate()函数中像这样访问开关:
val switch = binding.navView.menu.findItem(R.id.nav_theme) as SwitchCompat
switch.setOnCheckedChangeListener { _, isChecked ->
}但是,它抛出了一个异常,即不能将MenuItem转换为SwitchCompat。
我没有看到任何其他方法来访问此交换机。
发布于 2021-06-23 01:38:24
如果要在项目上启用开关,请使用actionViewClass定义组件。如果你没有弄错,你可以删除app:actionLayout="@layout/theme_switch"
app:actionViewClass="androidx.appcompat.widget.SwitchCompat"https://stackoverflow.com/questions/68087825
复制相似问题