大概樣子
首先要寫一個(gè)徽章布局notifications_badge.xm
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:id="@+id/notifications_badge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top|center_horizontal"
android:layout_marginLeft="26dp"
android:layout_marginTop="14dp"
android:background="@drawable/notification_badge"
android:gravity="center"
android:text="1+"
android:textColor="@color/white"
android:textSize="16sp" />
</merge>
notification_badge是用shape畫的紅色圓點(diǎn)
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<size
android:width="28sp"
android:height="28sp" />
<solid android:color="@color/read" />
</shape>
然后stackoverflow中答案封裝成簡單的工具類,如下.
public class BNVNotifacationBadgeUtil {
/**
* 添加消息徽章
*
* @param itemIndex 表示添加到第幾個(gè)ItemView
* @param desc 每個(gè)徽章上的內(nèi)容是啥
*/
public static void addNotificationBadge(BottomNavigationView mBNV, int itemIndex, String desc) {
BottomNavigationItemView mCurrentItemView = getBottomNavigationItemView(mBNV, itemIndex);
LayoutInflater.from(mBNV.getContext()).inflate(R.layout.layout_notification_badge, mCurrentItemView, true);
TextView mBadge = (TextView) mCurrentItemView.findViewById(R.id.notifications_badge);
if (mBadge != null) {
mBadge.setText(desc);
}
}
/**
* 移除消息徽章
*
* @param itemIndex
*/
public static void removeNotificationBadge(BottomNavigationView mBNV, int itemIndex) {
BottomNavigationItemView mCurrentItemView = getBottomNavigationItemView(mBNV, itemIndex);
TextView mBadge = (TextView) mCurrentItemView.findViewById(R.id.notifications_badge);
if (mBadge != null) {
((ViewGroup) mBadge.getParent()).removeView(mBadge);
}
}
/**
* 修改消息徽章上面的內(nèi)容
*
* @param itemIndex
* @param desc
*/
public static void modifyNotificationBadgeContent(BottomNavigationView mBNV, int itemIndex, String desc) {
BottomNavigationItemView mCurrentItemView = getBottomNavigationItemView(mBNV, itemIndex);
TextView mBadge = (TextView) mCurrentItemView.findViewById(R.id.notifications_badge);
if (mBadge != null) {
mBadge.setText(desc);
}
}
/**
* 判斷當(dāng)前索引對應(yīng)的ItemView中是否有徽章
*
* @param mBNV
* @param itemIndex
*/
public static Boolean judgeBadgeExist(BottomNavigationView mBNV, int itemIndex) {
BottomNavigationItemView mCurrentItemView = getBottomNavigationItemView(mBNV, itemIndex);
TextView mBadge = (TextView) mCurrentItemView.findViewById(R.id.notifications_badge);
if (mBadge == null) {
return false;
} else {
return true;
}
}
/**
* 獲取當(dāng)前索引對應(yīng)的ItemView對象
*
* @param mBNV
* @param itemIndex
* @return
*/
private static BottomNavigationItemView getBottomNavigationItemView(BottomNavigationView mBNV, int itemIndex) {
BottomNavigationMenuView bottomNavigationMenuView = (BottomNavigationMenuView) mBNV.getChildAt(0);
return (BottomNavigationItemView) bottomNavigationMenuView.getChildAt(itemIndex);
}
}