Material库纯文字BottomNavigationView能否移除图标内边距并居中文字
BottomNavigationView默认面向“图标+文字”的组合结构设计,即使不给导航项设置任何图标,也会保留图标对应的预留高度和内边距,默认配置下没法直接让纯文字垂直居中。下面是两种可落地的实现方案:
方案一:自定义导航项布局(推荐,完全实现文字居中效果)
这个方案直接替换默认的导航项布局,能彻底移除图标预留空间,自由控制文字位置:
- 新建纯文字的导航项布局,比如命名为
nav_item_text_only.xml:
<?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:textColor="@color/nav_text_color_selector" android:textSize="14sp" />
- 在
BottomNavigationView的布局配置中绑定自定义布局,同时强制显示文字标签:
<com.google.android.material.bottomnavigation.BottomNavigationView android:id="@+id/bottom_nav_view" android:layout_width="match_parent" android:layout_height="wrap_content" app:itemCustomLayout="@layout/nav_item_text_only" app:labelVisibilityMode="labeled" />
- 正常在菜单资源中定义各导航项的标题即可,此时所有文字会自动在导航栏范围内垂直、水平居中。
方案二:调整默认布局参数(不想改自定义布局时使用)
如果不想替换默认布局,没法完全消除图标预留内边距,但可以通过调整参数避免文字被截断:
- 直接调整导航栏整体高度,默认导航高度为
80dp,可根据文字大小设置合适的固定高度,比如60dp:
<com.google.android.material.bottomnavigation.BottomNavigationView android:layout_width="match_parent" android:layout_height="60dp" app:labelVisibilityMode="labeled" />
- 压缩导航项的上下内边距,减少非必要的空白:
app:itemPaddingTop="2dp" app:itemPaddingBottom="2dp"
- 调整文字样式,避免行高过大导致截断,可通过
app:itemTextAppearance自定义文字的大小、行高参数。
注意事项
- 自定义布局时,文字的选中/未选中状态颜色可通过
app:itemTextColor绑定颜色选择器实现,不需要在自定义布局里额外设置。 app:itemCustomLayout属性需要Material库版本在1.4.0及以上,低版本可先升级依赖。
内容的提问来源于stack exchange,提问作者urGoose
相关产品推荐
相关产品推荐

