This solution works by letting android create the tabs then calculating the total width of them. Then checks if the tabs will fit the screen width, if it will fit then sets the tabMode to "fixed" which scales all the tabs to fit the screen width.
The tab layout xml, parent doesn't matter:
<com.google.android.material.tabs.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="scrollable"/>
Then in your activity onCreate or fragment 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
}
If you are using TabLayout with Viewpager, then you have to set a layoutChangeListener since the tabs are not inflated at the start.
In your activity onCreate or fragment 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
}
}
Note: If you want all of your tabs to have same text size when the tabMode is "fixed", then you have to set the textSize manually from styles.xml.