You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中如何实现BadgeDrawable≤10显原值、>10显10+?

解决BadgeDrawable显示10+的问题

BadgeDrawable的number属性仅支持整数设置,无法直接显示"10+"这类自定义文本。要实现需求,需通过badgeText属性自定义文本,同时根据数字大小切换显示逻辑:

  • 当count ≤ 10时,用number属性显示具体数字
  • 当count > 10时,设置badgeText为"10+",并将number设为0(避免默认数字干扰显示)

修改后的代码如下:

dataBind.tabLayout.getTabAt(positions)?.apply {
    val badge = orCreateBadge
    badge.isVisible = count != 0
    
    if (count > 10) {
        badge.badgeText = "10+"
        badge.number = 0
    } else {
        badge.number = count
        badge.badgeText = null
    }
    
    badge.backgroundColor = if (!tabCheck) {
        resources.getColor(R.color.main_accent)
    } else {
        resources.getColor(R.color.gray_card)
    }
    badge.badgeTextColor = resources.getColor(R.color.white)
}

关键说明:

  • 直接用orCreateBadge获取BadgeDrawable实例,减少空判断冗余
  • 设置自定义badgeText时必须重置number为0,否则会优先显示number值
  • 仅在count != 0时开启isVisible,避免空徽章占位

内容的提问来源于stack exchange,提问作者Niraj Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 02:20:38