Android BottomNavigationView添加消息
2021-11-29 本文已影响0人
hao_developer
大概样子
image.png
首先要写一个徽章布局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画的红色圆点
<?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 表示添加到第几个ItemView
* @param desc 每个徽章上的内容是啥
*/
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);
}
}
/**
* 修改消息徽章上面的内容
*
* @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);
}
}
/**
* 判断当前索引对应的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;
}
}
/**
* 获取当前索引对应的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);
}
}