I have added TabLayout
(from support library v22.2.1) to my Fragment as:
I guess this is the simpliest way to achieve what you want.
public class CustomTabLayout extends TabLayout {
public CustomTabLayout(Context context) {
super(context);
}
public CustomTabLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomTabLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
try {
if (getTabCount() == 0)
return;
Field field = TabLayout.class.getDeclaredField("mTabMinWidth");
field.setAccessible(true);
field.set(this, (int) (getMeasuredWidth() / (float) getTabCount()));
} catch (Exception e) {
e.printStackTrace();
}
}
}
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
app:tabMode="scrollable"/>
try with this changes
<android.support.design.widget.TabLayout
android:id="@+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabGravity="fill" />
This is my solution with tabMode set to: app:tabMode="scrollable"
class MyTabLayout(
context: Context,
attrs: AttributeSet?
) : TabLayout(context, attrs) {
override fun onMeasure(
widthMeasureSpec: Int,
heightMeasureSpec: Int
) {
val equalTabWidth= (MeasureSpec.getSize(widthMeasureSpec) / tabCount.toFloat()).toInt()
for (index in 0..tabCount) {
val tab = getTabAt(index)
val tabMeasuredWidth = tab?.view?.measuredWidth ?: equalTabWidth
if (tabMeasuredWidth < equalTabWidth) {
tab?.view?.minimumWidth = equalTabWidth
}
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
}
}
After spending 2 days to figure out the issue, now finally it's working for me. Please see @Tyler V's answer check here From Tyler's answer 'It was key to set the minimum width before calling super.onMeasure().' is very important
I didn't care about the tabs filling the width, but I cared that the background color wasn't expanding to the full width. So I thought of this solution, where I put a FrameLayout behind it with the same background color as the tabs.
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/MyColor">
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
style="@style/MyCustomTabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="scrollable"/>
</FrameLayout>