如何为BottomNavigationView的选中项添加顶部选中栏
方法一:自定义Drawable作为Item背景(简单高效)
这种方法通过自定义状态选择器,让选中的item顶部显示指定颜色的横条,无需额外代码逻辑。
- 在
res/drawable目录下创建bottom_nav_item_bg.xml文件:
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <!-- 选中状态:显示顶部横条 --> <item android:state_checked="true"> <layer-list> <item android:top="0dp" android:left="0dp" android:right="0dp" android:height="4dp"> <shape android:shape="rectangle"> <solid android:color="@color/your_selected_color"/> <!-- 替换为你的选中颜色 --> </shape> </item> <!-- 透明背景,避免遮挡item原有内容 --> <item android:top="4dp"> <shape android:shape="rectangle"> <solid android:color="@android:color/transparent"/> </shape> </item> </layer-list> </item> <!-- 未选中状态:透明背景 --> <item android:state_checked="false"> <shape android:shape="rectangle"> <solid android:color="@android:color/transparent"/> </shape> </item> </selector>
- 在布局文件中给BottomNavigationView设置该背景:
<com.google.android.material.bottomnavigation.BottomNavigationView android:id="@+id/bottom_nav" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/white" app:menu="@menu/bottom_nav_menu" app:itemBackground="@drawable/bottom_nav_item_bg" app:itemIconTint="@color/bottom_nav_tint" <!-- 可选:设置图标颜色 --> app:itemTextColor="@color/bottom_nav_tint"/> <!-- 可选:设置文字颜色 -->
注意:确保你的menu文件中每个item都设置了
app:checkable="true",否则选中状态不会生效。
方法二:动态顶部指示器(支持动画与灵活定制)
如果需要更灵活的样式(比如自定义宽度、滑动动画),可以通过添加独立的View作为指示器,配合代码动态控制位置。
- 用ConstraintLayout包裹BottomNavigationView和指示器View:
<androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <!-- 顶部选中指示器 --> <View android:id="@+id/nav_indicator" android:layout_width="60dp" android:layout_height="4dp" android:background="@color/your_selected_color" app:layout_constraintTop_toTopOf="@id/bottom_nav"/> <com.google.android.material.bottomnavigation.BottomNavigationView android:id="@+id/bottom_nav" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/white" app:menu="@menu/bottom_nav_menu" app:itemIconTint="@color/bottom_nav_tint" app:itemTextColor="@color/bottom_nav_tint"/> </androidx.constraintlayout.widget.ConstraintLayout>
- 在代码中监听选中事件,动态调整指示器位置:
val bottomNav = findViewById<BottomNavigationView>(R.id.bottom_nav) val indicator = findViewById<View>(R.id.nav_indicator) // 初始化指示器宽度为单个item的宽度 val itemWidth = resources.displayMetrics.widthPixels / bottomNav.menu.size() indicator.layoutParams.width = itemWidth indicator.x = 0f // 默认选中第一个item bottomNav.setOnItemSelectedListener { menuItem -> val position = bottomNav.menu.indexOf(menuItem) // 带动画移动指示器到对应item位置 indicator.animate() .x((position * itemWidth).toFloat()) .setDuration(200) .start() true }
优化点:如果item宽度不一致,可通过
bottomNav.menu.getItem(position).view获取item的View,再用view.left和view.width来精准设置指示器的位置与宽度。
内容的提问来源于stack exchange,提问作者Vishnu Satheesh
相关产品推荐
相关产品推荐

