Kotlin BottomNavigationView添加角标(BadgeView)

效果

在这里插入图片描述

思路

获取整个BottomNavigationView菜单,再根据下标获取某一个子菜单tab,然后给这个tab添加我们自定义的view,可以是数字也可以是文字。


代码

    /**
     * 给BottomNavigationView 设置Badge 小红点
     *
     * BottomNavigationMenuView中的每一个Tab是一个FrameLayout,所以可以在上面随意添加View、这样就可以实现角标了
     */
    private fun setBadge() {
        //获取底部菜单view
        val menuView = bottom_navigation.getChildAt(0) as BottomNavigationMenuView
        //获取第2个itemView
        val itemView = menuView.getChildAt(1) as BottomNavigationItemView
        //引入badgeView
        val badgeView =  LayoutInflater.from(this).inflate(R.layout.layout_badge_view, menuView, false)
        //把badgeView添加到itemView中
        itemView.addView(badgeView)
        //获取子view并设置显示数目
        val count = badgeView.findViewById<TextView>(R.id.tv_badge)
        count.text = "2"

        //不显示则隐藏
        //count.visibility=View.GONE
    }

layout_badge_view就是自定义的一个layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tv_badge"
        android:layout_width="@dimen/dp_18"
        android:layout_height="@dimen/dp_18"
        android:layout_gravity="center"
        android:layout_marginLeft="@dimen/dp_10"
        android:layout_marginTop="@dimen/dp_2"
        android:background="@drawable/shape_oval_primary"
        android:gravity="center"
        android:includeFontPadding="false"
        android:text="1"
        android:textColor="@color/white" />

</LinearLayout>

shape_oval_primary是一个背景为主题色的圆

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval"
    android:useLevel="false">

    <solid android:color="@color/colorPrimary" />
    <stroke
        android:width="0dp"
        android:color="@color/white" />
    <size
        android:width="10dp"
        android:height="10dp" />

</shape>

github:https://github.com/yechaoa/wanandroid_kotlin

发布了248 篇原创文章 · 获赞 446 · 访问量 69万+

猜你喜欢

转载自blog.csdn.net/yechaoa/article/details/103977127