<com.google.android.material.tabs.TabLayout
android:id="@+id/tabGridMaterial"
android:layout_width="0dp"
android:layout_height="@dimen/dp_27"
android:background="@android:color/white"
app:tabMode="scrollable"
android:layout_marginStart="@dimen/dp_17"
android:layout_marginEnd="@dimen/dp_17"
android:layout_marginTop="@dimen/dp_20"
app:layout_constraintTop_toBottomOf="@+id/tvGridName"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:tabIndicatorHeight="0dp"
app:tabPaddingStart="0dp"
app:tabPaddingEnd="0dp"
app:tabPaddingTop="0dp"
app:tabPaddingBottom="0dp"
app:tabMaxWidth="@dimen/dp_43"
android:visibility="invisible"
tools:visibility="visible"
app:tabRippleColor="@null"
app:tabTextAppearance="@style/MyTabLayout"
app:tabTextColor="@color/color_1B1C1E" />
<androidx.viewpager2.widget.ViewPager2
android:id="@+id/rvGridMaterial"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/dp_20"
android:layout_marginStart="@dimen/dp_17"
android:visibility="invisible"
tools:visibility="visible"
android:layout_marginEnd="@dimen/dp_17"
app:layout_constraintTop_toBottomOf="@+id/tabGridMaterial"
tools:background="@color/color_B2000000"
tools:layout_height="@dimen/dp_100" />
TabLayoutMediator(tabGridMaterial,rvGridMaterial) { tab, position ->
val customView=LayoutInflater.from(context).inflate(R.layout.layout_tab_featured_grid,tabGridMaterial,false)
val tvTabFeaturedGrid=customView.findViewById<AppCompatTextView>(R.id.tvTabFeaturedGrid)
tvTabFeaturedGrid.text=indexStr[position]
tab.customView = customView
}.attach()
<androidx.appcompat.widget.LinearLayoutCompat 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="wrap_content">
<androidx.appcompat.widget.AppCompatTextView
android:id="@+id/tvTabFeaturedGrid"
android:layout_width="@dimen/dp_34"
android:layout_height="@dimen/dp_27"
android:background="@drawable/selector_tab_featured_grid"
android:gravity="center"
android:textColor="@color/selector_text_color_tab_featured_grid"
android:textSize="@dimen/sp_14" />
</androidx.appcompat.widget.LinearLayoutCompat>
注意點
設置tab間距 ,tab自定義布局與tabMaxWidth 配合使用