Android BottomNavigationView添加角标
2021-02-25 本文已影响0人
可乐_JS
BottomNavigationView角标效果图.png
插入角标代码:
@SuppressLint("RestrictedApi")
private void setBNV_Badge(int position, int num) {
if (num <= 0) {
return;
}
BottomNavigationMenuView menuView = (BottomNavigationMenuView) mBinding.bnv.getChildAt(0);
if (null == menuView) {
return;
}
if (position > menuView.getChildCount() - 1) {
return;
}
BottomNavigationItemView itemView = (BottomNavigationItemView) menuView.getChildAt(position);
View badge = LayoutInflater.from(this).inflate(R.layout.layout_badge, itemView, false);
TextView numView = badge.findViewById(R.id.tv_badge_num);
UnreadMsgUtil.show(numView, num);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
lp.leftMargin = menuView.getItemIconSize();
lp.bottomMargin = SizeUtils.dp2px(28);//BottomNavigationView的高度为50dp
itemView.addView(badge, lp);
}
调用代码:
setBNV_Badge(0, 1);
setBNV_Badge(1, 100);
setBNV_Badge(2, 0);
角标布局xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tv_badge_num"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/bg_ff2a39"
android:gravity="center"
android:layout_gravity="center"
android:minWidth="@dimen/dp_15"
android:minHeight="@dimen/dp_15"
android:textColor="@color/color_FFFFFF"
android:visibility="visible"
android:textSize="@dimen/sp_8"
tools:text="99+" />
</FrameLayout>
UnreadMsgUtil代码:
/**
* ================================
* Des:未读角标工具类
* Created by kele on 2021/2/25.
* E-mail:984127585@qq.com
* ================================
*/
public class UnreadMsgUtil {
public static void show(TextView numView, int num) {
if (numView == null) {
return;
}
ViewGroup.LayoutParams lp = numView.getLayoutParams();
DisplayMetrics dm = numView.getResources().getDisplayMetrics();
numView.setVisibility(View.VISIBLE);
if (num > 0 && num < 10) {//圆
lp.width = (int) (15 * dm.density);
numView.setText(num + "");
} else if (num > 9 && num < 100) {//圆角矩形,圆角是高度的一半,设置默认padding
lp.width = RelativeLayout.LayoutParams.WRAP_CONTENT;
numView.setPadding((int) (6 * dm.density), 0, (int) (6 * dm.density), 0);
numView.setText(num + "");
} else {//数字超过两位,显示99+
lp.width = RelativeLayout.LayoutParams.WRAP_CONTENT;
numView.setPadding((int) (6 * dm.density), 0, (int) (6 * dm.density), 0);
numView.setText("99+");
}
numView.setLayoutParams(lp);
}
}
dp2px代码:
public static int dp2px(final float dpValue) {
final float scale = Resources.getSystem().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}