android center align the selected tab in tablayout

Shumin Gao picture Shumin Gao · Aug 19, 2015 · Viewed 10k times · Source

I am using android support design tablayout. Here's my code:

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

    <android.support.v4.view.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />

My issue is the tabs always align left. However, I would like to center the selected tab (even at the beginning, the first(selected) tab should be centered). Is there a way to do this? Thanks.

Answer

Lubos Horacek picture Lubos Horacek · Apr 27, 2016

I took a look into TabLayout and tabContentStart only sets padding for its first child -> SlidingTabStrip, so I set it manually on both sides:

public class CenteringTabLayout extends TabLayout {
    public CenteringTabLayout(Context context) {
        super(context);
    }

    public CenteringTabLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CenteringTabLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        View firstTab = ((ViewGroup)getChildAt(0)).getChildAt(0);
        View lastTab = ((ViewGroup)getChildAt(0)).getChildAt(((ViewGroup)getChildAt(0)).getChildCount()-1);
        ViewCompat.setPaddingRelative(getChildAt(0), (getWidth()/2) - (firstTab.getWidth()/2),0,(getWidth()/2) - (lastTab.getWidth()/2),0);
    }
}

TabLayout's first 0 index child is the SlidingTabStrip.