xml的展现
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="48dp"
android:background="?android:attr/windowBackground"
android:longClickable="true"
android:theme="@style/bottom_navigation_style"
app:labelVisibilityMode="labeled"
app:layout_constraintBottom_toBottomOf="parent"
app:menu="@menu/bottom_navigation" />
app:menu
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/navigation_home"
android:icon="@mipmap/ic_main_home"
android:title="@string/main_home" />
<item
android:id="@+id/navigation_shop"
android:icon="@mipmap/ic_main_shop"
android:title="@string/main_shop" />
<item
android:id="@+id/navigation_msg"
android:icon="@mipmap/ic_main_msg"
android:title="@string/main_msg" />
<item
android:id="@+id/navigation_mine"
android:icon="@mipmap/ic_main_mine"
android:title="@string/main_mine" />
</menu>
上面的xml就是底部导航的菜单
问题1:选中和未选中的图标和文字颜色配置
需要设置主题android:theme
<style name="bottom_navigation_style" parent="LctTheme">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="android:textColorSecondary">@android:color/black</item>
</style>
colorPrimary为图标和文字的选中颜色
android:textColorSecondary为图标和文字的未选中颜色
问题2:给某一个菜单增加小红点或者未读标识
MenuBadge.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_marginTop="@dimen/space_h"
android:layout_marginStart="@dimen/space_xh"
android:id="@+id/msgCount"
android:layout_width="5dp"
android:layout_height="5dp"
android:layout_gravity="center"
android:gravity="center"
android:textColor="@color/white"
android:textSize="@dimen/text_m"
app:bl_shape="oval"
app:bl_solid_color="@color/colorPrimary" />
</LinearLayout>
下面是在activity的使用
private val badgeView by lazy { MenuBadgeBinding.inflate(layoutInflater, null, false) }
/**
* 给BottomNavigationView 设置Badge 小红点
*/
private fun setBadge() {
//获取底部菜单view
val menuView = binding.bottomNavigation.getChildAt(0) as BottomNavigationMenuView
//获取第2个itemView
val itemView = menuView.getChildAt(2) as BottomNavigationItemView
//把badgeView添加到itemView中
itemView.addView(badgeView.root)
}
问题3:底部导航栏长按会吐司
参数就是 BottomNavigationView 的菜单ID 集合
fun BottomNavigationView.clearToast(ids: MutableList<Int>) {
val bottomNavigationMenuView: ViewGroup = (this.getChildAt(0) as ViewGroup)
//遍历子View,重写长按点击事
for (position in 0 until ids.size) {
bottomNavigationMenuView.getChildAt(position).findViewById<View>(ids[position])
.setOnLongClickListener { true }
}
}