Tabs don't fit to screen with tabmode=scrollable, Even with a Custom Tab Layout

后端 未结 3 1661
轻奢々
轻奢々 2020-12-04 00:01

I have made a custom TabLayout with a ViewPager and am using the TabLayout in scrollable mode:

I need it to be scrollable as the number of dates can var

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-04 00:54

    Here is my solution.

    public class MyTabLayout extends TabLayout {    
        public MyTabLayout(Context context) {
            super(context);
        }
    
        public MyTabLayout(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public MyTabLayout(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }
    
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    
            ViewGroup tabLayout = (ViewGroup)getChildAt(0);
    
            int childCount = tabLayout.getChildCount();
    
            int widths[] = new int[childCount+1];
    
            for(int i = 0; i < childCount; i++){
                widths[i] = tabLayout.getChildAt(i).getMeasuredWidth();
                widths[childCount] += widths[i];
            }
    
            int measuredWidth = getMeasuredWidth();
            for(int i = 0; i < childCount; i++){
                tabLayout.getChildAt(i).setMinimumWidth(measuredWidth*widths[i]/widths[childCount]);
            }
    
        }
    
    }
    

提交回复
热议问题