从BottomNavigation中移除徽章

时间:2018-01-25 12:10:41

标签: android android-bottomnav

我已根据following thread实施了计数器徽章。

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

2 个答案:

答案 0 :(得分:2)

找到解决方案。

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

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

答案 1 :(得分:0)

就我而言,我在徽章视图中添加了 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)
    }
}