主要是给TabLayout设置背景,设置margin
先看效果图
上面的是默认样式,下面是自定义样式并设置了margin
如何设置margin
主要是通过获取tabLayout的子控件,然后动态修改margin
fun reflexPadding(tabLayout: TabLayout) {
tabLayout.post {
try {
//拿到tabLayout的mTabStrip属性
val mTabStrip = tabLayout.getChildAt(0) as LinearLayout
val margin: Int = UIUtils.dp2px(6f)
val marginStart: Int = UIUtils.dp2px(16f)
for (i in 0 until mTabStrip.childCount) {
val tabView = mTabStrip.getChildAt(i)
//设置tab左右间距为10dp 注意这里不能使用Padding 因为源码中线的宽度是根据 tabView的宽度来设置的
val params =
tabView.layoutParams as LinearLayout.LayoutParams
when (i) {
0 -> {
params.leftMargin = marginStart
params.rightMargin = margin
}
mTabStrip.childCount - 1 -> {
params.leftMargin = margin
params.rightMargin = marginStart
}
else -> {
params.leftMargin = margin
params.rightMargin = margin
}
}
tabView.setPadding(UIUtils.dp2px(10f), 0, UIUtils.dp2px(10f), 0)
tabView.layoutParams = params
tabView.invalidate()
}
} catch (e: Exception) {
Log.d("???", "???")
e.printStackTrace()
}
}
}
代码示例
<com.google.android.material.tabs.TabLayout
android:id="@+id/tab_normal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
app:tabMode="scrollable"/>
<com.google.android.material.tabs.TabLayout
android:id="@+id/tab_custom_bg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabBackground="@drawable/shape_tab_bg"
app:tabRippleColor="@color/transparent"
app:tabGravity="fill"
app:tabIndicatorHeight="0dp"
app:tabMode="scrollable"
app:tabSelectedTextColor="@color/color_3D8361"
app:tabTextColor="@color/color_1D2129_30"/>
private val titles = arrayOf("欧冠","英超","西甲","意甲","德甲","法甲","中超","欧联杯","皇马","巴萨","拜仁","利物浦")
@SuppressLint("MissingInflatedId")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_custom_tab)
val tabNormal = findViewById<TabLayout>(R.id.tab_normal)
val tabCustomBg = findViewById<TabLayout>(R.id.tab_custom_bg)
for (name in titles) {
tabNormal.addTab(tabNormal.newTab().setText(name))
tabCustomBg.addTab(tabCustomBg.newTab().setText(name))
}
TabLayoutUtil.reflexPadding(tabCustomBg)
}
源码地址:GitHub - zhoulei519/MyTest
demo中还有很多其他小工具,欢迎查看