如何在导航抽屉中创建可选标题

问题描述 投票:0回答:1

在我的应用程序中,我正在以编程方式填充NavigationView菜单,如

val menu = navigation.menu
menu.setGroupCheckable(MENU_GROUP, true, true)
val subMenu = menu.addSubMenu(MENU_GROUP, 0, 0, "New group")

subMenu.add(0, 0, 0, "item 1").apply { isCheckable = true }
subMenu.add(0, 1, 1, "item 2").apply { isCheckable = true }
subMenu.add(0, 2, 2, "item 3").apply { isCheckable = true }
subMenu.add(0, 3, 3, "item 4").apply { isCheckable = true }

val subMenu1 = menu.addSubMenu(MENU_GROUP, 1, 1, "New group 2")
subMenu1.add(1, 0, 0, "item 1").apply { isCheckable = true }
subMenu1.add(1, 1, 1, "item 2").apply { isCheckable = true }
subMenu1.add(1, 2, 2, "item 3").apply { isCheckable = true }
subMenu1.add(1, 3, 3, "item 4").apply { isCheckable = true }

这使我可以选择那些“项目*” MenuItem中的任何一个,但是我无法选择任何SubMenu标头。

Here is a visual explanation

According to this

可检查项目仅出现在子菜单或上下文菜单中。

这是我对它的理解,但是我很难找到解决方法。物料成分NavigationView特别是does different cases for these two types of menu's

我当前的解决方案实质上是重新实现具有普通视图的菜单来实现此目的。有什么办法可以避免这种情况,只是让SubMenu可以直接选择/检查?

java android kotlin navigationview
1个回答
1
投票

Navigation Drawer不支持可选标题。但是我们可以使用众所周知的库MaterialDrawer来实现此目的。

我将为您简化设置

依赖关系:

implementation "com.mikepenz:materialdrawer:7.0.0"
implementation 'com.google.android.material:material:1.0.0'
implementation "androidx.recyclerview:recyclerview:1.1.0"
implementation "androidx.annotation:annotation:1.1.0"
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'

您可能已经在项目中拥有其中一些依赖关系,因此无需再次添加它们

只需将此添加到要在其中添加抽屉的onCreateActivity

DrawerBuilder()
        .withActivity(this)
        .withToolbar(toolbar)
        .addDrawerItems(
            SecondaryDrawerItem().withName("New group"),
            PrimaryDrawerItem().withName("Item 1").withIcon(R.drawable.ic_icon),
            PrimaryDrawerItem().withName("Item 2").withIcon(R.drawable.ic_icon),
            PrimaryDrawerItem().withName("Item 3").withIcon(R.drawable.ic_icon),
            DividerDrawerItem(),
            SecondaryDrawerItem().withName("New group 2"),
            PrimaryDrawerItem().withName("Item 1").withIcon(R.drawable.ic_icon),
            PrimaryDrawerItem().withName("Item 2").withIcon(R.drawable.ic_icon),
            PrimaryDrawerItem().withName("Item 3").withIcon(R.drawable.ic_icon)
        )
        .build()

您可以找到很多自定义信息here,在存储库中的sample app也包含很多这些自定义信息。

结果将是这样的

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.