2

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

然后,当通知计数为 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 时徽章没有被移除,我似乎无法找出原因。

4

2 回答 2

4

找到了解决方案。

我在菜单项中找到实际的徽章并在最终生成新徽章之前将其删除。这是唯一适合我的方法:

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)
    }
}
于 2018-01-26T09:41:44.123 回答
0

就我而言,我添加TAG了 badgeView 并通过 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)
    }
}
于 2021-06-15T14:23:30.987 回答