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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章