TabLayout设置Indicator下划线长度贴文字显示

本文介绍如何通过Java代码自定义TabLayout组件的下划线长度,使其能够适应不同长度的文字标签,并保持美观一致的视觉效果。文章提供了一个实用的方法setIndicator,用于动态调整下划线宽度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

        mTabTop.post(new Runnable() {
            @Override
            public void run() {
                TabIndicatorUtils.setIndicator(mTabTop, DisplayUtils.sp2px(getActivity(), 16));
            }
        });

import android.graphics.Paint;
import android.support.design.widget.TabLayout;
import android.view.View;
import android.widget.LinearLayout;

import java.lang.reflect.Field;

/**
 * Created by Administrator on 2018/7/31.
 */

public class TabIndicatorUtils {

    /**
     * 修改TabLayout的下划线长度
     * 单位px
     */
    public static void setIndicator(TabLayout tabs, int textSize) {

        Paint paint = new Paint();
        paint.setTextSize(textSize);
        float textWidth = paint.measureText((String) tabs.getTag());
        int padding = (int) ((tabs.getWidth() / tabs.getTabCount() - textWidth) / 2);
        Class<?> tabLayout = tabs.getClass();
        Field tabStrip = null;
        try {
            tabStrip = tabLayout.getDeclaredField("mTabStrip");
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

        tabStrip.setAccessible(true);
        LinearLayout llTab = null;
        try {
            llTab = (LinearLayout) tabStrip.get(tabs);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }


        for (int i = 0; i < llTab.getChildCount(); i++) {
            View child = llTab.getChildAt(i);
            child.setPadding(0, 0, 0, 0);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
            params.leftMargin = padding;
            params.rightMargin = padding;
            child.setLayoutParams(params);
            child.invalidate();
        }
    }

}
<android.support.design.widget.TabLayout
            android:id="@+id/tabtop"
            android:layout_width="220dp"
            android:layout_height="match_parent"
            android:background="@color/CN36"
            android:tag="1哈哈哈"
            app:tabIndicatorColor="@color/white"
            app:tabIndicatorHeight="2dp"
            app:tabMode="fixed"
            app:tabSelectedTextColor="@color/white"
            app:tabTextAppearance="@style/TabLayoutTextHomeStyle"
            app:tabTextColor="@drawable/selector_text_choice_white" />

因为Tablayout每个字tab的宽度是一致的,所以需要根据子tab里最长的文字进行设置下划线的长度。xml里面的tag就是设置的最长tab的文字。

tabMode需要设置fixed。

tab间距根据控件总长度以及最长文字的宽度计算。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值