TabLayout的Indicator自定義寬度

方法一 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

 

所以我採用的是方法一,本來想考慮方法三點,但是項目沒有引用到MagicIndictor,所以就不考慮了。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章