此解决方案的工作原理是让 android 创建选项卡,然后计算它们的总宽度。然后检查选项卡是否适合屏幕宽度,如果适合则将 tabMode 设置为“固定”,这会缩放所有选项卡以适合屏幕宽度。
标签布局xml,父无关系:
<com.google.android.material.tabs.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="scrollable"/>
然后在您的活动中 onCreate 或片段 onCreateView:
var totalWidth = 0
var maxWidth = 0
for (i in 0 until tabLayout.tabCount) {
val tabWidth = (tabLayout.getChildAt(0) as ViewGroup).getChildAt(i)!!.width
totalWidth += tabWidth
maxWidth = max(maxWidth, tabWidth)
}
val screenWidth = Resources.getSystem().displayMetrics.widthPixels
if (totalWidth < screenWidth&& screenWidth/ tabLayout.tabCount >= maxWidth) {
tabLayout.tabMode = TabLayout.MODE_FIXED
}
如果您将 TabLayout 与 Viewpager 一起使用,那么您必须设置一个 layoutChangeListener,因为选项卡在开始时不会膨胀。
在您的活动 onCreate 或片段 onCreateView 中:
tabLayout.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ ->
var totalWidth = 0
var maxWidth = 0
for (i in 0 until tabLayout.tabCount) {
val tabWidth = (tabLayout.getChildAt(0) as ViewGroup).getChildAt(i)!!.width
totalWidth += tabWidth
maxWidth = max(maxWidth, tabWidth)
}
val screenWidth = Resources.getSystem().displayMetrics.widthPixels
if (totalWidth < screenWidth && screenWidth / tabLayout.tabCount >= maxWidth) {
tabLayout.tabMode = TabLayout.MODE_FIXED
}
}
注意:如果您希望所有选项卡在 tabMode 为“固定”时具有相同的文本大小,那么您必须从 styles.xml 手动设置 textSize。