设计图如下:
方法一 XML设置Indicator的宽度
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:width="12dp"
android:height="3dp"
android:gravity="center_horizontal">
<shape>
<solid android:color="@color/white" />
</shape>
</item>
</layer-list>
不过有API要求23起,不过我们最低target是21,不管了。
如果实在要兼容更低版本,可以定义一个默认的xml和一个v23的xml来实现对低版本的兼容,低版本由于没有height和width,考虑设置left和right来达到对indicator宽度的限制。
例如:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:left="25dp"
android:right="25dp"
android:gravity="center_horizontal">
<shape>
<solid android:color="@color/white" />
</shape>
</item>
</layer-list>
使用:app:tabIndicator="@drawable/tab_indicator"
方法二 反射设置Indicator宽度
internal class TabIndicatorRectF(private val indicatorBoundsModifier: IndicatorBoundsModifier) : RectF(), Serializable {
private val temp: RectF = RectF()
interface IndicatorBoundsModifier {
fun modify(bounds: RectF?)
}
override fun set(left: Float, top: Float, right: Float, bottom: Float) {
temp.set(left, top, right, bottom)
indicatorBoundsModifier.modify(temp)
super.set(temp)
}
fun replaceBoundsRectF(tabLayout: TabLayout?) {
try {
val field: Field = TabLayout::class.java.getDeclaredField("tabViewContentBounds")
field.isAccessible = true
field.set(tabLayout, this)
} catch (e: NoSuchFieldException) {
e.printStackTrace()
} catch (e: IllegalAccessException) {
e.printStackTrace()
}
}
class FixedWidthModifier(width: Float) : IndicatorBoundsModifier {
private val halfWidth = abs(width) / 2
override fun modify(bounds: RectF?) {
bounds?.centerX()?.let {
bounds.left = it - halfWidth
bounds.right = it + halfWidth
}
}
}
}
调用:
TabIndicatorRectF(TabIndicatorRectF.FixedWidthModifier(DisplayUtil.dip2px(12f)))
.replaceBoundsRectF(toolbarFuncBinding.tabLayout)
方法三 使用第三方库实现:MageicIndictor
方法四:自定义Indictor
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<item android:gravity="center">
<shape>
<size
android:width="12dp"
android:height="4dp" />
<solid android:color="@color/color_333" />
</shape>
</item>
</layer-list>
<com.google.android.material.tabs.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="40dp"
app:tabIndicatorFullWidth="false"
app:tabMode="fixed"
app:tabIndicatorGravity="bottom"
app:tabGravity="center"
app:tabIndicator="@drawable/tab_indicator_black"
app:tabIndicatorColor="@color/color_333"/>
所以我采用的是方法四,本来想考虑方法三点,但是项目没有引用到MagicIndictor,所以就不考虑了。
部分参考自:https://cloud.tencent.com/developer/article/1460300