Realize that the TabLayout subscript is as long as the text, and the selected font size changes

Android uses the system TabLayout to achieve the effect of subscript and text equal length

Android uses the system TabLayout to achieve changing the Tab selected state style

void setTabLyout(){
        setTabPadding(tablayout,resetMeasureW(7));
        tablayout.addOnTabSelectedListener(onTabSelectedListener);
}

TabLayout.OnTabSelectedListener onTabSelectedListener = new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            setTabSelect(tab);
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
            tab.setCustomView(null);
        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    };

void setTabSelect(TabLayout.Tab tab) { //设置选中后显示的布局
        TextView textView = new TextView(getActivity());
        textView.setTextSize(18);
        textView.setGravity(Gravity.CENTER);
        textView.setTextColor(getResources().getColor(R.color.bgf_textred));
        textView.setText(tab.getText());
        TextPaint tp = textView.getPaint();
        tp.setFakeBoldText(true);
        tab.setCustomView(textView);
    }

 /**
     * 动态计算文字宽度设置指示器宽度
     * @param tabLayout
     * @param padding 相邻tab的间距
     */
    public static void setTabPadding(final TabLayout tabLayout, final int padding) {
        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                //拿到tabLayout的mTabStrip属性
                LinearLayout mTabStrip = (LinearLayout) tabLayout.getChildAt(0);
                for (int i = 0; i < mTabStrip.getChildCount(); i++) {
                    View tabView = mTabStrip.getChildAt(i);
                    //拿到tabView的mTextView属性  tab的字数不固定一定用反射取mTextView
                    tabView.setPadding(0, 0, 0, 0);
                    //设置tab左右间距 注意这里不能使用Padding 因为源码中线的宽度是根据 tabView的宽度来设置的
                    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tabView.getLayoutParams();
                    params.width = LinearLayout.LayoutParams.WRAP_CONTENT;
                    params.leftMargin = padding;
                    params.rightMargin = padding;
                    tabView.setLayoutParams(params);
                    tabView.invalidate();
                }
            }
        });

    }

  /**
     * 按750设计图 比例 获取实际宽度
     */
    public static int resetMeasureW(int w) {
        int screenWidth = getScreenWidth(getApplication());
        double mW = w * screenWidth / 375.0;

        return (int) mW;
    }
//屏幕分辨率
    public static DisplayMetrics getDisplayMetrics(Context context) {
        return context.getResources().getDisplayMetrics();
    }
  //屏幕宽度
    public static int getScreenWidth(Context context) {
        return getDisplayMetrics(context).widthPixels;
    }

Guess you like

Origin blog.csdn.net/qq_35644925/article/details/125222580