从底部导航栏中移除徽章

3

我根据以下主题实现了一个计数器徽章。

然后我稍微扩展了一下,当通知计数为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时,徽章没有被移除,我似乎找不到原因。

问题出在哪里?显然你对 bottomNavigationItemView.addView(inboxBadge); 做了相反的操作...而且如果计数为0,膨胀视图有什么意义呢? - undefined
编辑后:现在你正在删除新添加的项目...显然这个项目并不存在于bottomNavigationItemView中...所以显然"什么都不会发生"... - undefined
明显的解决方案:1. 只创建一次inboxBadge 2. 存储对它的引用 3. 利用 setVisibility - undefined
@Selvin 我也尝试过在全局声明徽章(应该指向同一个实例),并在删除时引用它。但这也没有帮助。 - undefined
请大家有点礼貌,解释一下你们的负评,而不是只是负评一个完全合理的问题。 - undefined
1
他确实有问题。为什么要踩他呢?在这行代码notificationCount.setVisibility(GONE);中,他设置了一个新实例化的notificationCount的可见性。看看他的回答,他删除了之前实例化的视图! - undefined
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)
    }
}

0
在我的情况下,我在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)
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接