I have added TabLayout
(from support library v22.2.1) to my Fragment as:
please use this it will solve this problem definitely
<android.support.design.widget.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMaxWidth="0dp"
app:tabGravity="fill"
app:tabMode="fixed" />
You should set app:tabMode="fixed" when you want to show tabs 'fill'.
**<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/toolbar"
android:background="#353535"
app:tabMode="fixed"
android:minHeight="?attr/actionBarSize"
app:tabIndicatorColor="@color/red"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />**
Here's an easier way to make sure that the width of tab is equal to tab's string length
<androidx.viewpager.widget.ViewPager
android:id="@+id/vpTabs"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.tabs.TabLayout
android:id="@+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMaxWidth="0dp"
app:tabMode="scrollable"/>
</androidx.viewpager.widget.ViewPager>
Following code is used:-
app:tabMaxWidth="0dp"
app:tabMode="scrollable"
You may used app:tabMaxWidth="0dp" in tablayout
@dtx12 answer doesn't work if any tab title is bigger than (measuredWidth/ tabCount).
There is my TabLayout
subclass for this situation (in Kotlin). I hope this will help someone.
class FullWidthTabLayout : TabLayout {
constructor(context: Context?) : super(context)
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
super.onLayout(changed, l, t, r, b)
if (changed) {
val widths = mutableListOf<Int>()
for (i in 0..this.tabCount - 1) {
widths.add(this.getTabAt(i)!!.customView!!.width)
}
if (widths.sum() < this.measuredWidth) {
var equalPart: Long = this.measuredWidth.toLong() / this.tabCount.toLong()
var biggerWidths = widths.filter { it > equalPart }
var smallerWidths = widths.filter { it <= equalPart }
var rest: Long = this.measuredWidth.toLong() - biggerWidths.sum()
while (biggerWidths.size != 0) {
equalPart = rest / smallerWidths.size
biggerWidths = smallerWidths.filter { it >= equalPart }
smallerWidths = smallerWidths.filter { it < equalPart }
rest -= biggerWidths.sum()
}
val minWidth = (rest / smallerWidths.size) + 10 //dont know why there is small gap on the end, thats why +10
for (i in 0..this.tabCount - 1) {
this.getTabAt(i)!!.customView!!.minimumWidth = minWidth.toInt()
}
}
}
}
}