【问题标题】:How to change the color of BottomNavigationView badge background?如何更改 BottomNavigationView 徽章背景的颜色?
【发布时间】:2020-02-18 15:06:54
【问题描述】:

我已经根据这个例子实现了带有徽章计数的BottomNavigationView https://stackoverflow.com/a/56340643/6699103

效果很好,但我想更改徽章的背景颜色 有什么办法吗?

【问题讨论】:

标签: android material-design bottomnavigationview material-components material-components-android


【解决方案1】:

根据导航项状态在 res/drawable 中为您想要的颜色创建可绘制选择器。例如 bottom_navigation_colors.xml :

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_checked="true"
        android:color="@color/white" />
    <item
        android:state_checked="false"
        android:color="@color/blue" />
</selector>

然后你可以为你的 BottomNavigationView 创建一个样式样式

<style name="myBottomNavigationStyle">
    <item name="android:background">#rrggbb</item>
    <item name="itemIconTint">@drawable/bottom_navigation_colors</item>
    <item name="itemTextColor">@drawable/bottom_navigation_colors</item>
</style>

并将其分配给BottomNavigationView

<com.google.android.material.bottomnavigation.BottomNavigationView
    android:id="@+id/ebottom_navigation_view"
    style="@style/myBottomNavigationStyle"
    .... />

【讨论】:

    【解决方案2】:

    这是我找到的解决方案,它按预期工作

    val profileBadge = bottomNavigationView.getOrCreateBadge(R.id.profile)
    
     profileBadge.number = profileCount
    
     profileBadge.backgroundColor = ContextCompat.getColor(this@HomeActivity, R.color.green) 
    

    【讨论】:

      【解决方案3】:

      只需使用徽章的setBackgroundColor()方法即可。

        BadgeDrawable badge = bottomNavigationView.getOrCreateBadge(menuItemId);
        badge.setNumber(..);
        badge.setBackgroundColor(....);
      

      如果您想在应用中全局更改样式,您可以在应用主题中定义 badgeStyle attr:

      <style name="AppTheme" parent="Theme.MaterialComponents.*">
        <item name="badgeStyle">@style/CustomBadge</item>
        ...
      </style>
      
      <style name="CustomBadge" parent="@style/Widget.MaterialComponents.Badge">
         <item name="backgroundColor">@color/.....</item>
      </style>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-05-16
        • 2015-06-03
        • 2019-04-02
        • 2022-01-08
        • 1970-01-01
        • 1970-01-01
        • 2011-11-11
        相关资源
        最近更新 更多