Android BottomNavigationView 添加消息提示(二)

这篇文章中使用的旧版本BottomNavigationView如何设置徽章
material-components-android简介

  • 依赖
implementation 'com.google.android.material:material:1.3.0-alpha03'
  • android:theme="@style/AppTheme"必须使用Theme.MaterialComponents.xxx主题
<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>
  • 布局
<com.google.android.material.bottomnavigation.BottomNavigationView
    android:id="@+id/bnvs"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/white"
    app:menu="@menu/bottom_nav_menu" />
  • 代码
/**
 * 设置徽章
 */
private fun setupBadging(index: Int, count: Int) {
    
    
    val mBnvs = findViewById<BottomNavigationView>(R.id.bnvs)
    var menuItemId = mBnvs.menu.getItem(index).itemId
    var badge = mBnvs.getOrCreateBadge(menuItemId)
    badge.isVisible = true
    badge.number = count // 设置数字
    // badge.badgeGravity = count// 设置红点点
}
/**
 * 增加徽章数字
 */
private fun addBadgingCount(index: Int, count: Int) {
    
    
    val mBnvs = findViewById<BottomNavigationView>(R.id.bnvs)
    var menuItemId = mBnvs.menu.getItem(index).itemId
    var badge = mBnvs.getOrCreateBadge(menuItemId)
    badge.isVisible = true
    badge.number = badge.number.plus(count) // 数字增加
}
/**
 * 清空数字并隐藏徽章
 */
private fun clearAndHideBadge(index: Int, count: Int) {
    
    
    val mBnvs = findViewById<BottomNavigationView>(R.id.bnvs)
    var menuItemId = mBnvs.menu.getItem(index).itemId
    var badge = mBnvs.getOrCreateBadge(menuItemId)
    badge.isVisible = false // 隐藏徽章
    badge.clearNumber() // 清空数字
}

猜你喜欢

转载自blog.csdn.net/MoLiao2046/article/details/110002437
今日推荐