Search code examples
androidandroid-support-libraryandroid-tablayout

TabLayout not filling width when tabMode set to 'scrollable'


I have added TabLayout (from support library v22.2.1) to my Fragment as:

<android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        style="@style/MyColorAccentTabLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="scrollable"/>

The issue is that when the Fragment's orientation is landscape (before or after the initial creation of the fragment), the TabLayout doesn't match the width of the Fragment (yes the parent has its width set to match_parent as well).

When screen width is small (i.e not all tabs can be shown at same time): enter image description here

When screen width is big enough to show all tabs (see the blank space at the right): enter image description here

If I change tabMode to fixed, width is filled but tabs are too small. Is there any proper solution out there?


Solution

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