Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove badge from BottomNavigation

I've implemented a counter badge according to the following thread.

Then I expended it a bit to remove the badge from the navigation item when notification count is 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()
}

Problem is that the badge isn't removed when notification count is 0, and I can't seem to find out why.

like image 938
Ambran Avatar asked Nov 27 '25 01:11

Ambran


1 Answers

Found a solution.

I'm locating the actual badge in the menu item and removing it before eventually producing a new one. It's the only approach that works for me:

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)
    }
}
like image 114
Ambran Avatar answered Nov 29 '25 15:11

Ambran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!