TabLayout not filling width when tabMode set to 'scrollable' TabLayout not filling width when tabMode set to 'scrollable' android android

TabLayout not filling width when tabMode set to 'scrollable'


Instead of creating custom TabLayout and hacking around or creating more layouts which acts as wrapper around TabLayout only for background. Try this,

<android.support.design.widget.TabLayout    android:id="@+id/tabs"    style="@style/MyColorAccentTabLayout"    android:layout_width="match_parent"    android:layout_height="wrap_content"    <!-- Instead of setting app:tabBackground -->    android:background="@color/colorAccent"    app:tabGravity="fill"    app:tabMode="scrollable"/>

This will set background to behind tabLayout instead of setting background behind every tab.


androidx version:

<androidx.viewpager.widget.ViewPager    android:id="@+id/view_pager"    android:layout_width="match_parent"    android:layout_height="match_parent"    app:layout_behavior="@string/appbar_scrolling_view_behavior" >    <com.google.android.material.tabs.TabLayout        android:id="@+id/tabs"        android:layout_width="match_parent"        android:layout_height="wrap_content"        app:tabMaxWidth="0dp"        app:tabGravity="fill"        app:tabMode="fixed"        /></androidx.viewpager.widget.ViewPager>

With more than 5 tabs

***** BELOW IS OLD ANSWER *****

Try this one, it's a workaround which sets tabMaxWidth="0dp", tabGravity="fill" and tabMode="fixed".

 <android.support.v4.view.ViewPager     android:id="@+id/container"     android:layout_width="match_parent"     android:layout_height="match_parent"     app:layout_behavior="@string/appbar_scrolling_view_behavior">     <android.support.design.widget.TabLayout         android:id="@+id/tabs"         android:layout_width="match_parent"         android:layout_height="wrap_content"         app:tabMaxWidth="0dp"         app:tabGravity="fill"         app:tabMode="fixed"/></android.support.v4.view.ViewPager>

Screenshot on a 10 inch tablet:

screenshot


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();        }    }}