Android如何修改BottomNavigationView底部导航选中指示器的宽度
解决方案
你之前在shape中设置width不生效,是因为作为itemBackground使用的drawable会默认填充整个BottomNavigationView子项的宽度,shape自身设置的宽度会被父布局的拉伸规则覆盖,可通过以下两种方式实现需求:
方案1:修改自定义selector(兼容低版本Material库)
调整activity_main_tab_background代码,通过inset标签设置左右边距间接控制指示器宽度:
<selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_checked="true"> <layer-list> <item android:gravity="top"> <!-- 调整insetLeft、insetRight数值即可控制指示器宽度,数值越大指示器越窄 --> <inset android:insetLeft="@dimen/_20fdp" android:insetRight="@dimen/_20fdp"> <shape android:shape="rectangle"> <size android:height="@dimen/_5fdp"/> <solid android:color="@color/red"/> <corners android:bottomLeftRadius="@dimen/_3fdp" android:bottomRightRadius="@dimen/_3fdp"/> </shape> </inset> </item> </layer-list> </item> </selector>
原有BottomNavigationView布局无需改动即可生效。
方案2:使用Material库自带指示器属性(推荐,Material Components 1.4.0+支持)
无需自定义selector,直接通过BottomNavigationView自带属性配置指示器,代码更简洁:
<com.google.android.material.bottomnavigation.BottomNavigationView android:id="@+id/main_bottom_nav" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" app:labelVisibilityMode="unlabeled" app:menu="@menu/home_bottom_nav" app:itemActiveIndicatorEnabled="true" app:itemActiveIndicatorColor="@color/red" app:itemActiveIndicatorHeight="@dimen/_5fdp" app:itemActiveIndicatorWidth="@dimen/_10fdp" app:itemActiveIndicatorCornerRadius="@dimen/_3fdp" app:itemActiveIndicatorGravity="top"/>
注意:使用该方案需移除原有
app:itemBackground属性配置。
内容的提问来源于stack exchange,提问作者Aayush Apporio
相关产品推荐
相关产品推荐

