【问题标题】:How to Create Selectable Headers in Navigation Drawer如何在导航抽屉中创建可选标题
【发布时间】:2019-12-28 16:41:40
【问题描述】:

在我的应用程序中,我正在以编程方式填充我的 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 }

这使我可以选择任何“项目 *”MenuItems,但我无法选择任何 SubMenu 标头。

According to this,

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

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

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

【问题讨论】:

    标签: java android kotlin navigationview


    【解决方案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'
    

    其中一些依赖项可能已经在您的项目中,您不需要再次添加它们

    只需将此添加到您要添加抽屉的ActivityonCreate

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

    您可以在 repo 中找到很多自定义信息 here sample app 也包含很多这些自定义。

    结果会是这样的

    【讨论】:

      猜你喜欢
      • 2016-01-22
      • 2014-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多