BottomNavigation徽章无法移除求助:通知数为0时徽章不消失
我一眼就看出问题出在哪了——你每次调用setInboxIcon方法时,都会重新inflate一个全新的inboxBadge实例,但这个新实例根本就没被添加到bottomNavigationItemView里,所以调用removeView(inboxBadge)自然不会有任何效果!
问题根源
你当前的逻辑存在一个关键漏洞:
- 每次调用方法都创建新的
inboxBadge对象 - 当
count > 0时,把这个新徽章添加到导航项 - 当
count == 0时,试图移除这个刚创建但从未被添加过的徽章,这当然无效
修正方案
把inboxBadge和notificationCount改成类的成员变量,只在第一次需要的时候初始化,确保我们始终操作同一个徽章实例:
// 将这两个变量提升为类的成员变量,避免重复创建 private var inboxBadge: View? = null private var notificationCount: TextView? = null fun setInboxIcon(count: Int) { val bottomNavigationMenuView = bottomNavigation.getChildAt(0) as BottomNavigationMenuView val bottomNavigationItemView = bottomNavigationMenuView.getChildAt(3) as BottomNavigationItemView // 仅在徽章未初始化时才创建实例 if (inboxBadge == null) { inboxBadge = LayoutInflater.from(context).inflate(R.layout.inbox_icon_layout, bottomNavigationMenuView, false) notificationCount = inboxBadge?.findViewById(R.id.notification_count) } if (count == 0) { // 移除已存在的徽章(先判断是否已添加到父视图) inboxBadge?.let { if (it.parent == bottomNavigationItemView) { bottomNavigationItemView.removeView(it) } } } else { inboxBadge?.let { // 如果徽章还没被添加,先添加到导航项 if (it.parent != bottomNavigationItemView) { bottomNavigationItemView.addView(it) } notificationCount?.visibility = View.VISIBLE notificationCount?.text = Math.min(count, 9).toString() } } bottomNavigation.invalidate() }
额外优化建议
- 确认
bottomNavigationMenuView.getChildAt(3)确实对应你的收件箱导航项,索引从0开始,别搞错了位置 - 如果追求更简洁的逻辑,也可以不用移除视图,直接通过
View.GONE/View.VISIBLE控制徽章的显示隐藏,这样避免频繁的视图添加/移除操作,性能更优 - 如果遇到UI刷新不及时的问题,可以尝试调用
bottomNavigation.postInvalidate()确保在主线程更新UI
内容的提问来源于stack exchange,提问作者Ambran
相关产品推荐
相关产品推荐

