注:使用新的属性需要设置
implementation 'com.android.support:design:28.0.0'
在布局里加入 TabLayout,默认是下划线的样式,可以使用 tabIndicatorGravity
属性设置为:bottom
(默认值,可以不用设置,指示器显示在底部)、 top
(指示器显示在顶部)、center
(指示器显示在中间)、stretch
(指示器高度拉伸铺满 item)。
<android.support.design.widget.TabLayout
android:id="@+id/tl"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabIndicatorColor="@color/colorPrimary"
app:tabIndicatorFullWidth="true"
<!-- 设置 Indicator 高度 -->
app:tabIndicatorHeight="2dp"
app:tabMode="scrollable" />
1. “app:tabIndicatorFullWidth” 属性
注意 app:tabIndicatorFullWidth="true"
属性,设为 true,是 Indicator 充满 item 的宽度:
设为 false 是 Indicator 保持和 item 的内容宽度一致:
2. 给 Indicator 设置边距
网上的做法一般是通过反射来设置 Indicator 的宽度,可以参见博客:
关于Android改变TabLayout 下划线(Indicator)宽度实践总结
不过我觉得可以使用 layer-list
来实现。
在 drawable
文件夹下新建一个 indicator.xml
文件:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
<!-- 设置左边距 -->
android:left="15dp"
<!-- 设置右边距 -->
android:right="15dp">
<!-- 注:这里需要一个空的 <shape /> 标签,否则会报错 -->
<shape />
</item>
</layer-list>
需要注意的是在 shape 里设置颜色是无效的,需要在布局文件里设置 Indica