android center align the selected tab in tablayout

后端 未结 4 487
感动是毒
感动是毒 2020-12-03 15:33

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

    

        
4条回答
  •  清歌不尽
    2020-12-03 15:59

    public class MyTabLayout extends TabLayout {
    
        public MyTabLayout(Context context, AttributeSet attrs) {
            super(context, attrs);
            setTabMode(MODE_SCROLLABLE);
        }
    
        @Override
        protected void onLayout(boolean changed, int l, int t, int r, int b) {
            super.onLayout(changed, l, t, r, b);
            if (!changed) return;
            int totalTabsWidth = 0;
            for (int i = 0; i < getTabCount(); i++)
                totalTabsWidth += ((ViewGroup) getChildAt(0)).getChildAt(i).getWidth();
            int padding = (getWidth() - totalTabsWidth) / 2;
            if (padding < 0) padding = 0;
            getChildAt(0).setPaddingRelative(padding, 0, padding, 0);
        }
    }
    

提交回复
热议问题