使用导航组件时,从BottomNavigationView中删除徽章

问题描述

我正在使用材质设计 BottomNavigationView 组件,并使用导航组件来进行片段过渡。

我当前面临的问题是我无法删除/隐藏徽章。当我们使用navigationComponent时,我不能使用setonNavigationItemSelectedListener,而是使用setupWithNavController,所以当我点击itemId时,如何知道我当前在哪个片段/ itemId上,并删除该特定itemId的徽章>

解决方法

创建选择器XML以更改所选菜单项的图标。假设它叫做bottom_item_selector

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/unchecked_item_drawable" android:state_checked="false"/>
    <item android:drawable="@drawable/checked_item_drawable" android:state_checked="true"/>
</selector>

然后在菜单XML中更改图标以使用此可绘制对象:

    <item
        android:id="@+id/.."
        android:icon="@drawable/bottom_item_selector"
        android:checkable="true"
        android:title=""/>

通过这种方式,您不必添加侦听器并显式调用NavigationUI

,

使用自定义NavigationItemSelectedListener,您将删除原始侦听器。但是,您可以使用NavigationUI.onNavDestinationSelected(it,navController)触发默认行为。

bottomNavigationView.setOnNavigationItemSelectedListener {
            when (it.itemId) {
                R.id.nav_xxxx -> {
                    // handle click
                    // .....
                }
            }
            NavigationUI.onNavDestinationSelected(it,navController)
            true
        }