我这里说下我的实现方式
1.首先是布局了
<com.google.android.material.bottomnavigation.BottomNavigationView android:id="@+id/bottom_bnv" style="@style/Widget.Design.BottomNavigationView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" app:itemIconSize="@dimen/dp_20" android:background="@color/color_ffffffff" android:minHeight="?attr/actionBarSize" app:labelVisibilityMode="labeled" app:elevation="@dimen/dp_0" app:menu="@menu/bottom_bar_menu" />
布局文件设置了一下基本的属性 我就不概括了
想要取消字体缩放添加下面的属性:
<dimen name="design_bottom_navigation_active_text_size" tools:override="true">12sp</dimen> <dimen name="design_bottom_navigation_text_size" tools:override="true">12sp</dimen>
然后就是显示逻辑了
1 首先我们要定义一个badge 布局
<?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_msg_count" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginStart="@dimen/dp_10" android:layout_marginTop="@dimen/dp_3" android:background="@drawable/bg_red_circle_10" android:gravity="center" android:minWidth="@dimen/dp_15" android:minHeight="@dimen/dp_15" android:padding="@dimen/dp_1" android:textColor="@color/color_ffffffff" android:textColorHint="@color/color_ffffffff" android:textSize="@dimen/sp_9" /> </LinearLayout>
这里就是我们的小红点
2.编写代码逻辑了
@SuppressLint("RestrictedApi")
public static void displayItemNum(final BottomNavigationView mBottomNavigationView, final int mPosition, final int mCount) {
try {
final int maxSize = mBottomNavigationView.getItemIconSize();
if (mPosition > maxSize || mPosition < 0) {
return;
}
//Acquisition child View BottomNavigationMenuView Objects
final BottomNavigationMenuView menuView = (BottomNavigationMenuView) mBottomNavigationView.getChildAt(0);
final View mTab = menuView.getChildAt(mPosition);
final BottomNavigationItemView itemView = (BottomNavigationItemView) mTab;
View mBadge = itemView.getChildAt(3);
if (mBadge == null) {
//避免重复添加创建
mBadge = LayoutInflater.from(mBottomNavigationView.getContext()).inflate(R.layout.bottom_bar_item_badge, menuView, false);
itemView.addView(mBadge);
}
final TextView mTv = mBadge.findViewById(R.id.tv_msg_count);
if (mCount <= 0) {
mTv.setVisibility(View.GONE);
mTv.setText(String.format("%s", mCount));
} else {
mTv.setVisibility(View.VISIBLE);
if (mCount > 99) {
mTv.setText(String.format("%s+", 99));
} else {
mTv.setText(String.format("%s", mCount));
}
}
} catch (Exception e) {
MyLogger.tagE(TAG, e.getMessage());
e.printStackTrace();
}
}
红色部分是关键 ,因为重复创建会造成天界了多个View 造成多个显示View 遮挡,其实就是创建多了一样的badge。
如果你显示超多4个的话建议限制icon大小。
app:itemIconSize="@dimen/dp_20" 这个属性也很总要 app:labelVisibilityMode="labeled"