实现效果
一、依赖配置
dependencies {
api("com.google.android.material:material:1.11.0")
}
二、使用
<com.google.android.material.tabs.TabLayout
android:id="@+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="32dp"
app:tabBackground="@null" // 去除点击时水波纹效果
app:tabIndicator="@drawable/layer_tab_indicator" // 自定义指示器
app:tabIndicatorColor="@color/colorAccent"
app:tabMode="scrollable" // 设置Tab可滚动
app:tabRippleColor="@null" /> // 去除点击时水波纹效果
layer_tab_indicator.xml
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:gravity="center">
<shape>
<size
android:width="16dp"
android:height="3dp" />
<solid android:color="@color/colorAccent" />
<corners android:radius="9dp" />
</shape>
</item>
</layer-list>
代码
mTabTitles.forEach {
val tabView = LayoutInflater.from(mActivity).inflate(R.layout.item_order_tab, null)
tabView.findViewById<TextView>(R.id.tv_tab).text = it
mTabLayout?.addTab(mTabLayout!!.newTab().setCustomView(tabView))
}
mTabLayout?.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
override fun onTabSelected(tab: TabLayout.Tab?) {
// Others
tab?.view?.findViewById<TextView>(R.id.tv_tab)?.setTextColor(Color.BLACK)
}
override fun onTabUnselected(tab: TabLayout.Tab?) {
tab?.view?.findViewById<TextView>(R.id.tv_tab)
?.setTextColor(resources.getColor(R.color.color9A9A9A, null))
}
override fun onTabReselected(tab: TabLayout.Tab?) {}
})
item_order_tab.xml
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="32dp">
<TextView
android:id="@+id/tv_tab"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center"
android:textSize="14sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>