如何修改Material 3 BottomNavigation激活项指示器的形状?
当然可以自定义Material 3 BottomNavigation的激活项指示器形状,以下是几种实用实现方式:
方式一:自定义Drawable+主题配置
创建一个自定义Drawable文件(例如custom_nav_indicator.xml),定义你需要的形状(比如圆角矩形、胶囊形等):
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="?attr/colorPrimary" /> <corners android:radius="16dp" /> <size android:height="4dp" /> </shape>
然后在App主题中覆盖指示器样式,指定这个自定义Drawable:
<style name="Theme.MyApp" parent="Theme.Material3.DayNight.NoActionBar"> <item name="bottomNavigationIndicatorStyle">@style/CustomBottomNavIndicator</item> </style> <style name="CustomBottomNavIndicator" parent="Widget.Material3.BottomNavigation.Indicator"> <item name="android:background">@drawable/custom_nav_indicator</item> </style>
方式二:代码动态替换
如果需要灵活控制(比如根据页面切换调整形状),可以通过代码获取指示器视图并替换背景:
val bottomNav = findViewById<BottomNavigationView>(R.id.bottom_nav) val indicator = bottomNav.findViewById<View>(com.google.android.material.R.id.navigation_bar_item_indicator) indicator.background = resources.getDrawable(R.drawable.custom_nav_indicator, theme)
方式三:自定义BottomNavigationView子类
如果需要结合动画或更复杂的绘制逻辑,可以继承BottomNavigationView,重写onDraw方法直接绘制自定义形状的指示器。
内容的提问来源于stack exchange,提问作者Amr Jyniat
相关产品推荐
相关产品推荐

