从 BottomNavigation 中移除徽章

Remove badge from BottomNavigation

我已经根据 实现了一个计数器徽章。

然后我稍微扩展了一下,在通知计数为 0 时从导航项中删除徽章:

fun setInboxIcon(count: Int) {
    val bottomNavigationMenuView = bottomNavigation.getChildAt(0) as BottomNavigationMenuView
    val bottomNavigationItemView = bottomNavigationMenuView.getChildAt(3) as BottomNavigationItemView
    val inboxBadge = LayoutInflater.from(context).inflate(R.layout.inbox_icon_layout, bottomNavigationMenuView, false)
    notificationCount = inboxBadge.findViewById(R.id.notification_count)

    if (count == 0) {
        notificationCount.visibility = GONE
        notificationCount.text = ""
        bottomNavigationItemView.removeView(inboxBadge) // <- nothing happens
    } else {
        notificationCount.visibility = VISIBLE
        notificationCount.text = Math.min(count, 9).toString()
        bottomNavigationItemView.addView(inboxBadge)
    }

    bottomNavigation.invalidate()
}

问题是当通知计数为 0 时徽章没有被删除,我似乎无法找出原因。

找到解决办法。

我正在菜单项中找到实际徽章并将其删除,然后最终生成一个新徽章。这是唯一对我有用的方法:

fun setInboxIcon(count: Int) {
    val bottomNavigationMenuView = bottomNavigation.getChildAt(0) as BottomNavigationMenuView
    val bottomNavigationItemView = bottomNavigationMenuView.getChildAt(3) as BottomNavigationItemView
    val badge = LayoutInflater.from(context).inflate(R.layout.inbox_icon_layout, bottomNavigationMenuView, false)
    val notificationCount = badge.findViewById(R.id.notification_count)

    // Reset current badge
    bottomNavigationItemView.removeView(bottomNavigationItemView.getChildAt(2))

    // Add new badge
    if (count > 0) {
        notificationCount.text = Math.min(count, 9).toString()
        bottomNavigationItemView.addView(badge)
    }
}

在我的例子中,我在 badgeView 中添加了 TAG 并通过 TAG 找到视图以将其删除。

private val TAG = "Badge"

fun addOrRemoveBadgeView(bottomNav: BottomNavigationView, show: Boolean) {
    val menuView = bottomNav.getChildAt(0) as BottomNavigationMenuView
    val itemView = menuView.getChildAt(3) as BottomNavigationItemView
    val notificationsBadge = LayoutInflater.from(bottomNav.context)
                                .inflate(R.layout.badge_layout,menuView, false)
    notificationsBadge.tag = TAG

    if (show) {
        itemView.addView(notificationsBadge)
    }
    else {
        val view = itemView.findViewWithTag<View>(TAG)
        itemView.removeView(view)
    }
}