关于Android改变TabLayout 下划线(Indicator)宽度实践总结

TabLayout 之改变 Indicator 的宽度 前言 默认情况下,TabLayout 中 Indicator 的宽度和该 Tab 的宽度相等。但是有时候我们需要自定义 Indicator 的宽度,所以本文将介绍改变 Indicator 的宽度的几种方法。 一、反射实现 第一种方法是通过反射的方式改变 Indicator 的宽度。 TabLayout 只提供了app:tabIndicatorHeight属性来设置 Indicator 的宽度,但没有提供设置宽度的 API。所以只能自己去修改了,先看下源码是怎么实现 Indicator 的。 .. 阅读详情

TabLayout我们再熟悉不过了,在开发中,像这种tab切换的需求都会用到TabLayout,它是由官方提供的一个控件,在support design 包中。使用起来非常简单方便,交互效果也很不错,能满足我们开发中95%的需求。但是它有一个缺陷:不能改变Tab下划线(Indicator)的宽度。本篇文章给你带来改变Tab下划线宽度的几种方式:

1 . 通过反射设置Tab下划线的宽度
2 . 通过TabLayout setCustomView 的方式
3 . 使用第三方开源库。

一、通过反射的方式,改变TabLayout下划线的宽度

首先我们看一下原生的TabLayout的效果(没有任何修改):

 

Tablayout.png

 

gif演示:

 

gif演示.gif

上图第一个固定模式(tabMode:fixed),下面是滚动模式(tabMode:scrollable),可以看到,所有Tab下方的线(即Indicator)是一样长的,不管Tab的内容是长还是短。Tab indicator的长度与最长的Tab保持一致。

TabLayout提供了tabIndicatorHeight 属性来设置indicator的高度,但是没有提供设置宽度的的api,要想改变indicator的宽度,就得去看看源码indicator是怎么实现的。简单的看一下源码:

思维导图.png

 

如上思维导图,其中有两个重点的东西, TabView 和 SlidingTabStrip,TabView就是我们所看到的Tab,SlidingTabStrip是TabView的父容器,继承自LinearLayout,用来处理Tab滑动相关操作,如动画,绘制Indicator等。

我们要研究indicator是怎么添加的,重点就在SlidingTabStrip 里了,这里我们看到了mSelectedIndicatorHeight,这就是我们设置Indicator的高度,在draw方法里有如下代码:

 @Override
        public void draw(Canvas canvas) {
            super.draw(canvas);

            // Thick colored underline below the current selection
            if (mIndicatorLeft >= 0 && mIndicatorRight > mIndicatorLeft) {
                canvas.drawRect(mIndicatorLeft, getHeight() - mSelectedIndicatorHeight,
                        mIndicatorRight, getHeight(), mSelectedIndicatorPaint);
            }
        }

这就是绘制的选中Tab的Indicator,高度是mSelectedIndicatorHeight,宽是mIndicatorRight - mIndicatorLeft 。那么者两个值是从哪儿来的呢?在updateIndicatorPosition方法中:

 private void updateIndicatorPosition() {
           // 选中的TabView
            final View selectedTitle = getChildAt(mSelectedPosition);
            int left, right;

            if (selectedTitle != null && selectedTitle.getWidth() > 0) {
                // left 和right 的值
                left = selectedTitle.getLeft();
                right = selectedTitle.getRight();

                if (mSelectionOffset > 0f && mSelectedPosition < getChildCount() - 1) {
                    // Draw the selection partway between the tabs
                    View nextTitle = getChildAt(mSelectedPosition + 1);
                    left = (int) (mSelectionOffset * nextTitle.getLeft() +
                            (1.0f - mSelectionOffset) * left);
                    right = (int) (mSelectionOffset * nextTitle.getRight() +
                            (1.0f - mSelectionOffset) * right);
                }
            } else {
                left = right = -1;
            }
           // 设置mIndicatorLeft和mIndicatorRight
            setIndicatorPosition(left, right);
        }

        void setIndicatorPosition(int left, int right) {
            if (left != mIndicatorLeft || right != mIndicatorRight) {
                // If the indicator's left/right has changed, invalidate
                mIndicatorLeft = left;
                mIndicatorRight = right;
                ViewCompat.postInvalidateOnAnimation(this);
            }
        }

从上面的代码就可以看出,Indicator(Tab选中下划线)的宽度其实就是TabView的宽度,那么TabView的宽度是多少呢?在SlidingTabStrip的onMeasure方法中,为TabView设置了宽度。请看代码:

 @Override
        protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
             ...
             //以上省略
            if (mMode == MODE_FIXED && mTabGravity == GRAVITY_CENTER) {
                final int count = getChildCount();

                // First we'll find the widest tab
               //google的工程师注释写的非常清楚:第一步,找出宽度最长的Tab
                int largestTabWidth = 0;
                for (int i = 0, z = count; i < z; i++) {
                    View child = getChildAt(i);
                    if (child.getVisibility() == VISIBLE) {
                        largestTabWidth = Math.max(largestTabWidth, child.getMeasuredWidth());
                    }
                }

                if (largestTabWidth <= 0) {
                    // If we don't have a largest child yet, skip until the next measure pass
                    return;
                }

                final int gutter = dpToPx(FIXED_WRAP_GUTTER_MIN);
                boolean remeasure = false;

                if (largestTabWidth * count <= getMeasuredWidth() - gutter * 2) {
                    // If the tabs fit within our width minus gutters, we will set all tabs to have
                    // the same width
                  // 第二步:将所有Tab的宽度都设置为largestTabWidth
                    for (int i = 0; i < count; i++) {
                        final LinearLayout.LayoutParams lp =
                                (LayoutParams) getChildAt(i).getLayoutParams();
                        if (lp.width != largestTabWidth || lp.weight != 0) {
                            lp.width = largestTabWidth;
                            lp.weight = 0;
                            remeasure = true;
                        }
                    }
                } else {
                    // If the tabs will wrap to be larger than the width minus gutters, we need
                    // to switch to GRAVITY_FILL
                    mTabGravity = GRAVITY_FILL;
                    updateTabViews(false);
                    remeasure = true;
                }

            ...
            //以下省略
            }
        }

这个方法很简单,一看就明白,有两个步骤:

 1, 一个for循环,找出宽度最大的一个TabView
 2, 再一个for 循环,设置所有TabView的宽度为最长那个TabView的宽度,即largestTabWidth

这就知道为什么前面提到的所有Tab 一样宽,不管长的还是短的。

另外一个点: 上面的onMeasure 中,执行的条件是mMode == MODE_FIXED && mTabGravity == GRAVITY_CENTER ,如果是其他条件,请看updateTabViews:

void updateTabViews(final boolean requestLayout) {
        for (int i = 0; i < mTabStrip.getChildCount(); i++) {
            View child = mTabStrip.getChildAt(i);
            child.setMinimumWidth(getTabMinWidth());
            updateTabViewLayoutParams((LinearLayout.LayoutParams) child.getLayoutParams());
            if (requestLayout) {
                child.requestLayout();
            }
        }
    }
    private void updateTabViewLayoutParams(LinearLayout.LayoutParams lp) {
        if (mMode == MODE_FIXED && mTabGravity == GRAVITY_FILL) {
            lp.width = 0;
            lp.weight = 1;
        } else {
            lp.width = LinearLayout.LayoutParams.WRAP_CONTENT;
            lp.weight = 0;
        }
    }

如果是MODE_FIXED,并且GRAVITY_FILL,则设置weight=1,所有TabView平分屏幕宽度,MODE_SCROLLABLE ,设置的WRAP_CONTENT 。

反射改变下划线宽度

思路:知道了绘制Indicator的宽度是根据TabView的宽度来决定的,那么我们设置TabView的宽度就能改变indicator的宽,TabView的宽由其中的mTextView决定,因此,通过反射得到mTextView,设置它的宽度,就能改变Indicator的宽度,这也是网上看到的大多数的解决方法。

上代码:

public static void setTabWidth(final TabLayout tabLayout, final int padding){
        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                try {
                    //拿到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
                        Field mTextViewField = tabView.getClass().getDeclaredField("mTextView");
                        mTextViewField.setAccessible(true);

                        TextView mTextView = (TextView) mTextViewField.get(tabView);

                        tabView.setPadding(0, 0, 0, 0);

                        //因为我想要的效果是   字多宽线就多宽,所以测量mTextView的宽度
                        int width = 0;
                        width = mTextView.getWidth();
                        if (width == 0) {
                            mTextView.measure(0, 0);
                            width = mTextView.getMeasuredWidth();
                        }

                        //设置tab左右间距 注意这里不能使用Padding 因为源码中线的宽度是根据 tabView的宽度来设置的
                        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tabView.getLayoutParams();
                        params.width = width ;
                        params.leftMargin = padding;
                        params.rightMargin = padding;
                        tabView.setLayoutParams(params);

                        tabView.invalidate();
                    }

                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        });

    }

效果图如下:

 

改变长度的Indicator演示.gif

提醒:这种方式改变Indicator最短也就Tab内容的宽度,如果设置很短,Tab内容就显示不下,如下图:

Tab内容显示不下.png

二、通过TabLayout setCustomView 的方式

第一种通过反射的方式设置Indicator宽度,最短只能Tab内容的宽度,如果设计师要所有选中的Tab下的Indicator都设置一个指定的宽度,这种就不行了。TabLayout可以设置自定义View,可以通过这种方法来达到目的。

1, 将TabLayout 的tabIndicatorHeight 设置为0
2,通过TabLayout 的setCustomView方式添加Tab
3, 在onTabSelected 回调种,处理Tab选中和未选中的状态;
4,为了方便使用,封装成一个通用的View

首先看布局:
enhance_tab_layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.design.widget.TabLayout
        android:id="@+id/enhance_tab_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabIndicatorHeight="0dp"
        >
    </android.support.design.widget.TabLayout>
</FrameLayout>

Tab item 布局:tab_item_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:id="@+id/tab_item_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="13sp"
    android:text="首页"
    android:textColor="#333333"
    />
<View
    android:id="@+id/tab_item_indicator"
    android:layout_width="30dp"
    android:layout_height="2dp"
    android:layout_marginTop="5dp"
    android:background="@color/colorAccent"
    android:visibility="invisible"
    />
</LinearLayout>

如上,TextView显示Tab内容,下面的View就是Tab下面的Indicator(下划线)。
自己定义的View,宽度随便你改。

添加Tab的时候使用setCustomView 方法:

 /**
     * 添加tab
     * @param tab
     */
    public void addTab(String tab){
        mTabList.add(tab);
        View customView = getTabView(getContext(),tab,mIndicatorWidth,mIndicatorHeight,mTabTextSize);
        mCustomViewList.add(customView);
        mTabLayout.addTab(mTabLayout.newTab().setCustomView(customView));
    }


    /**
     * 获取Tab 显示的内容
     *
     * @param context
     * @param
     * @return
     */
    public static View getTabView(Context context,String text,int indicatorWidth,int indicatorHeight,int textSize) {
        View view = LayoutInflater.from(context).inflate(R.layout.tab_item_layout, null);
        TextView tabText = (TextView) view.findViewById(R.id.tab_item_text);
        if(indicatorWidth>0){
            View indicator = view.findViewById(R.id.tab_item_indicator);
            ViewGroup.LayoutParams layoutParams = indicator.getLayoutParams();
            layoutParams.width  = indicatorWidth;
            layoutParams.height = indicatorHeight;
            indicator.setLayoutParams(layoutParams);
        }
        tabText.setTextSize(textSize);
        tabText.setText(text);
        return view;
    }

然后在onTabSelected中处理状态:

  @Override
        public void onTabSelected(TabLayout.Tab tab) {
            mViewPager.setCurrentItem(tab.getPosition());
            EnhanceTabLayout mTabLayout = mTabLayoutRef.get();
            if(mTabLayoutRef!=null){
                List<View> customViewList = mTabLayout.getCustomViewList();
                if(customViewList == null || customViewList.size() ==0){
                    return;
                }
                for (int i=0;i<customViewList.size();i++){
                    View view = customViewList.get(i);
                    if(view == null){
                        return;
                    }
                    TextView text = (TextView) view.findViewById(R.id.tab_item_text);
                    View indicator = view.findViewById(R.id.tab_item_indicator);
                    if(i == tab.getPosition()){ // 选中状态
                        text.setTextColor(mTabLayout.mSelectTextColor);
                        indicator.setBackgroundColor(mTabLayout.mSelectIndicatorColor);
                        indicator.setVisibility(View.VISIBLE);
                    }else{// 未选中状态
                        text.setTextColor(mTabLayout.mUnSelectTextColor);
                        indicator.setVisibility(View.INVISIBLE);
                    }
                }
            }

        }

代码其实挺简单的,但是如果项目中多处使用到,都这样来处理的话,就显得麻烦,因此,我们通过自定义View的方式将这些代码疯转成1个通用的TabLayoutView。如下:

EnhanceTabLayout.java

/**
 *  对 support Design 包中的TabLayout包装
 *  主要实现功能:更改indicator 的长度
 * Created by zhouwei on 2018/5/18.
 */

public class EnhanceTabLayout extends FrameLayout {
    private TabLayout mTabLayout;
    private List<String> mTabList;
    private List<View> mCustomViewList;
    private int mSelectIndicatorColor;
    private int mSelectTextColor;
    private int mUnSelectTextColor;
    private int mIndicatorHeight;
    private int mIndicatorWidth;
    private int mTabMode;
    private int mTabTextSize;

    public EnhanceTabLayout(@NonNull Context context) {
        super(context);
        init(context,null);
    }

    public EnhanceTabLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context,attrs);
    }

    public EnhanceTabLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context,attrs);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public EnhanceTabLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context,attrs);
    }

    private void readAttr(Context context,AttributeSet attrs){
        TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.EnhanceTabLayout);
        mSelectIndicatorColor = typedArray.getColor(R.styleable.EnhanceTabLayout_tabIndicatorColor,context.getResources().getColor(R.color.colorAccent));
        mUnSelectTextColor =  typedArray.getColor(R.styleable.EnhanceTabLayout_tabTextColor, Color.parseColor("#666666"));
        mSelectTextColor = typedArray.getColor(R.styleable.EnhanceTabLayout_tabSelectTextColor,context.getResources().getColor(R.color.colorAccent));
        mIndicatorHeight = typedArray.getDimensionPixelSize(R.styleable.EnhanceTabLayout_tabIndicatorHeight,1);
        mIndicatorWidth = typedArray.getDimensionPixelSize(R.styleable.EnhanceTabLayout_tabIndicatorWidth,0);
        mTabTextSize = typedArray.getDimensionPixelSize(R.styleable.EnhanceTabLayout_tabTextSize,13);
        mTabMode = typedArray.getInt(R.styleable.EnhanceTabLayout_tab_Mode,2);
        typedArray.recycle();
    }

    private void init(Context context,AttributeSet attrs){
        readAttr(context,attrs);

        mTabList = new ArrayList<>();
        mCustomViewList = new ArrayList<>();
        View view = LayoutInflater.from(getContext()).inflate(R.layout.enhance_tab_layout,this,true);
        mTabLayout = view.findViewById(R.id.enhance_tab_view);

        // 添加属性
        mTabLayout.setTabMode(mTabMode == 1 ? TabLayout.MODE_FIXED:TabLayout.MODE_SCROLLABLE);
        mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                // onTabItemSelected(tab.getPosition());
                // Tab 选中之后,改变各个Tab的状态
                for (int i=0;i<mTabLayout.getTabCount();i++){
                    View view = mTabLayout.getTabAt(i).getCustomView();
                    if(view == null){
                        return;
                    }
                    TextView text = (TextView) view.findViewById(R.id.tab_item_text);
                    View indicator = view.findViewById(R.id.tab_item_indicator);
                    if(i == tab.getPosition()){ // 选中状态
                        text.setTextColor(mSelectTextColor);
                        indicator.setBackgroundColor(mSelectIndicatorColor);
                        indicator.setVisibility(View.VISIBLE);
                    }else{// 未选中状态
                        text.setTextColor(mUnSelectTextColor);
                        indicator.setVisibility(View.INVISIBLE);
                    }
                }

            }

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

            }

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

            }
        });
    }

    public List<View> getCustomViewList(){
        return mCustomViewList;
    }

    public void addOnTabSelectedListener (TabLayout.OnTabSelectedListener onTabSelectedListener){
        mTabLayout.addOnTabSelectedListener(onTabSelectedListener);
    }

    /**
     * 与TabLayout 联动
     * @param viewPager
     */
    public void setupWithViewPager(@Nullable ViewPager viewPager) {
        mTabLayout.addOnTabSelectedListener(new ViewPagerOnTabSelectedListener(viewPager,this));
    }




    /**
     * retrive TabLayout Instance
     * @return
     */
    public TabLayout getTabLayout(){
        return mTabLayout;
    }

    /**
     * 添加tab
     * @param tab
     */
    public void addTab(String tab){
        mTabList.add(tab);
        View customView = getTabView(getContext(),tab,mIndicatorWidth,mIndicatorHeight,mTabTextSize);
        mCustomViewList.add(customView);
        mTabLayout.addTab(mTabLayout.newTab().setCustomView(customView));
    }

    public static class ViewPagerOnTabSelectedListener implements TabLayout.OnTabSelectedListener{

        private final ViewPager mViewPager;
        private final WeakReference<EnhanceTabLayout> mTabLayoutRef;

        public ViewPagerOnTabSelectedListener(ViewPager viewPager,EnhanceTabLayout enhanceTabLayout) {
            mViewPager = viewPager;
            mTabLayoutRef = new WeakReference<EnhanceTabLayout>(enhanceTabLayout);
        }

        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            mViewPager.setCurrentItem(tab.getPosition());
            EnhanceTabLayout mTabLayout = mTabLayoutRef.get();
            if(mTabLayoutRef!=null){
                List<View> customViewList = mTabLayout.getCustomViewList();
                if(customViewList == null || customViewList.size() ==0){
                    return;
                }
                for (int i=0;i<customViewList.size();i++){
                    View view = customViewList.get(i);
                    if(view == null){
                        return;
                    }
                    TextView text = (TextView) view.findViewById(R.id.tab_item_text);
                    View indicator = view.findViewById(R.id.tab_item_indicator);
                    if(i == tab.getPosition()){ // 选中状态
                        text.setTextColor(mTabLayout.mSelectTextColor);
                        indicator.setBackgroundColor(mTabLayout.mSelectIndicatorColor);
                        indicator.setVisibility(View.VISIBLE);
                    }else{// 未选中状态
                        text.setTextColor(mTabLayout.mUnSelectTextColor);
                        indicator.setVisibility(View.INVISIBLE);
                    }
                }
            }

        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
            // No-op
        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {
            // No-op
        }
    }

    /**
     * 获取Tab 显示的内容
     *
     * @param context
     * @param
     * @return
     */
    public static View getTabView(Context context,String text,int indicatorWidth,int indicatorHeight,int textSize) {
        View view = LayoutInflater.from(context).inflate(R.layout.tab_item_layout, null);
        TextView tabText = (TextView) view.findViewById(R.id.tab_item_text);
        if(indicatorWidth>0){
            View indicator = view.findViewById(R.id.tab_item_indicator);
            ViewGroup.LayoutParams layoutParams = indicator.getLayoutParams();
            layoutParams.width  = indicatorWidth;
            layoutParams.height = indicatorHeight;
            indicator.setLayoutParams(layoutParams);
        }
        tabText.setTextSize(textSize);
        tabText.setText(text);
        return view;
    }

暴露了一些常用方法和原生TabLayout 的几个重要属性,自定义属性如下:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <declare-styleable name="EnhanceTabLayout">
        <attr name="tab_Mode" format="enum">
            <enum name="mode_fixed" value="1"/>
            <enum name="mode_scrollable" value="2"/>
        </attr>
        <attr name="tabIndicatorColor" format="color"/>
        <attr name="tabSelectTextColor" format="color"/>
        <attr name="tabTextColor" format="color"/>
        <attr name="tabIndicatorHeight" format="dimension"/>
        <attr name="tabIndicatorWidth" format="dimension"/>
        <attr name="tabTextSize" format="dimension"/>
    </declare-styleable>
</resources>

好了,这样就封装了一个可以改变Indicator 宽度的TabLayout,看一下怎么用,xml布局如下:

 <com.example.codoon.customtablayout.EnhanceTabLayout
       android:id="@+id/enhance_tab_layout"
       android:layout_marginTop="30dp"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       app:tabIndicatorHeight="2dp"
       app:tabIndicatorWidth="30dp"
       app:tabTextColor="#999999"
       app:tab_Mode="mode_scrollable"
       app:tabSelectTextColor="@color/colorPrimary"
       app:tabIndicatorColor="@color/colorPrimary"
       app:tabTextSize="6sp"
       >

   </com.example.codoon.customtablayout.EnhanceTabLayout>

Activity中代码如下:

        mEnhanceTabLayout = findViewById(R.id.enhance_tab_layout);
        mEnhanceTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                 Log.e("log","onTabSelected");
            }

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

            }

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

            }
        });
        for(int i=0;i<sTitle.length;i++){
            mEnhanceTabLayout.addTab(sTitle[i]);
        }
        mEnhanceTabLayout.setupWithViewPager(mViewPager);
        List<Fragment> fragments = new ArrayList<>();
        for(int i=0;i<sTitle.length;i++){
            fragments.add(ItemFragment.newInstance(sTitle[i]));
        }

        MyAdapter adapter = new MyAdapter(getSupportFragmentManager(),fragments, Arrays.asList(sTitle));
        mViewPager.setAdapter(adapter);
        mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mEnhanceTabLayout.getTabLayout()));
        mEnhanceTabLayout.setupWithViewPager(mViewPager);

注意,如果是配合ViewPager使用,需要下面两行代码,单独使用则不需要:

 mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mEnhanceTabLayout.getTabLayout()));
 mEnhanceTabLayout.setupWithViewPager(mViewPager);

最后看一下效果:(图中第二个TabLayout)

自定义View方式.gif

三、第三方开源库

如果前面2中方式都满足不了你的需求的话,你可以使用第三方库,也有一些不错的开源库,这里推荐2个。
**1 , MagicIndicator **

github:https://github.com/hackware1993/MagicIndicator
star:4.4k

MagicIndicator ,使用方便,还有多种模式可以选择。包括:

 

indicator.png

 

有兴趣的可以去试一下。

repositories {
    ...
    maven {
        url "https://jitpack.io"
    }
}

dependencies {
    ...
    compile 'com.github.hackware1993:MagicIndicator:1.5.0'
}

布局文件:

<net.lucode.hackware.magicindicator.MagicIndicator
      android:id="@+id/magic_indicator"
      android:layout_width="match_parent"
      android:layout_height="49dp">

  </net.lucode.hackware.magicindicator.MagicIndicator>

代码中:

  MagicIndicator magicIndicator = (MagicIndicator) findViewById(R.id.magic_indicator);
        CommonNavigator commonNavigator = new CommonNavigator(this);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {

            @Override
            public int getCount() {
                return sTitle == null ? 0 : sTitle.length;
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                ColorTransitionPagerTitleView colorTransitionPagerTitleView = new ColorTransitionPagerTitleView(context);
                colorTransitionPagerTitleView.setNormalColor(Color.GRAY);
                colorTransitionPagerTitleView.setSelectedColor(Color.BLACK);
                colorTransitionPagerTitleView.setText(sTitle[index]);
                colorTransitionPagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mViewPager.setCurrentItem(index);
                    }
                });
                return colorTransitionPagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator indicator = new LinePagerIndicator(context);
                indicator.setMode(LinePagerIndicator.MODE_EXACTLY);
                //设置indicator的宽度
                indicator.setLineWidth(TabUtils.dp2px(context,20));
                return indicator;
            }
        });
        magicIndicator.setNavigator(commonNavigator);
        ViewPagerHelper.bind(magicIndicator,mViewPager);

效果图如下,图中最后一个TabLayout:

 

MagicIndicator.gif

2 , FlycoTabLayout
github:https://github.com/H07000223/FlycoTabLayout
star:6.5k

功能和MagicIndicator差不多,都支持多种Indicator效果:

FlycoTabLayout.gif

具体使用请看github 详细介绍。

四、总结

本文总结了改变TabLayout下划线(indicator)宽度的几种方式,使用的时候根据自己的需求选择,在原生控件能做的情况下,尽量使用原生控件,毕竟导入三方库需要一些额外的成本。如果你还有更好的方式,欢迎评论区留言讨论。

 



作者:依然范特稀西
链接:https://www.jianshu.com/p/83922d08250b
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

Android TabLayout -- 反射修改TabLayout下划线(Indicator)宽度失效的问题 在使用TabLayout的时,常常会遇到修改下划线(indicator)的需求,但是源码并没有提供修改宽度的api,而是始终和最长的下划线宽度保持一致,这点可以在源码里得出结论,源码如下(api26后源码有修改,这也就是为什么网上很多修改宽度方法失效的原因,不过思路都是一样的,本篇博客基于api28) 下划线主要由这个类SlidingTabIndicator实现,它是TabLayout的一个内部... 阅读详情

相关推荐

【Android】TabLayout 自定义指示器 Indicator 样式,kotlin中文版

app:tabIndicatorHeight=“2dp” app:tabMode=“scrollable” /> 1. “app:tabIndicatorFullWidth” 属性 注意 app:tabIndicatorFullWidth="true" 属性,设为 true,是 Indicator 充满 item 的宽度: [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-wQNsE8ob-1639839992958)(https://user-gold-cdn.xitu.

m0_65512599的博客 2067

【Android】TabLayout 自定义指示器 Indicator 样式

在布局里加入 TabLayout <android.support.design.widget.TabLayout android:id="@+id/tl" android:layout_width="match_parent" android:layout_height="wrap_content" app:tabIndicatorColor="@color...

DawnYu 1万+

Android 实践总结:自定义 TabLayout 下划线宽度

默认情况下,TabLayout 在选中的标签下方会显示一条下划线,用于突出当前选中的标签。通过自定义的 CustomTabLayout 类,我们可以灵活地控制下划线的宽度,以满足不同的设计需求。要实现自定义下划线宽度,我们需要创建一个自定义的 TabLayout,继承自 TabLayout 类。获取 TabLayout 的测量宽度,然后根据标签数量计算出自定义宽度,这里示例中设定为总宽度的 60%。上述代码中,我们设置了 TabLayout 的一些基本属性,包括宽度、高度、标签模式、标签位置等。

Byte_O_O的博客 587

一篇文章带你解决Android-TabLayout缺陷,不同方式带你改变Tab下划线宽度【实践总结】

相信大多数从事Android开发的朋友们越来越发现,找工作越来越难了,面试的要求越来越高了除了基础扎实的java知识,数据结构算法,设计模式还要求会底层源码,NDK技术,性能调优,还有会些小程序和跨平台,比如说flutter,以思维脑图的方式展示在下图;《互联网大厂面试真题解析、进阶开发核心学习笔记、全套讲解视频、实战项目源码讲义》点击传送门即可获取!Android开发知识点,真正体系化!**

2401_84149635的博客 1003

Android设置TabLayout及下划线宽度

不过,使用动态的话,如果不设置相关的属性,是不能达到两个选项各自占长度一半,还得给Tablayout加上下列属性。先是通过findviewbyid方法找到实例,之后调用tablayout的newTab方法来创建tab。最后根据 android:width=“40dp” 就可以设置指定的宽度,我这里是40dp。app:tabMaxWidth=“xxdp” 设置最大的tab宽度。app:tabMinWidth=“xxdp” 设置最小的tab宽度。app:tabMod 设置Tab模式。Tablayout的使用。

知道的越多,不知道的越多。 3090

什么是以太网链路聚合

以太网链路聚合技术通过将多个物理端口捆绑成逻辑端口,可显著提升网络性能。该技术能增加总带宽(各链路带宽之和)、提高可靠性(故障秒级切换)并实现智能负载分担。主要分为手工模式和基于LACP协议的动态模式,后者能检测链路故障更可靠。配置时需确保接口参数一致、模式匹配,适用于核心交换、服务器接入等场景。华为设备通过创建Eth-Trunk接口、指定LACP模式并添加成员接口即可完成部署。这项成熟技术能以低成本解决带宽瓶颈和可靠性问题,是构建高速稳定网络的关键方案。

lai_2020的博客 684

Android中TabLayout修改下划线指示器的宽度

项目中有个需求要用到TabLayout控件,在适配Indicator下划线指示器的宽度时,我采用的方式是: app:tabIndicatorFullWidth="false" 即宽度与item文字的宽度一致,若设为true,则Indicator 充满 item 的宽度。 后来项目UI把下划线指示器的宽度调整为某个固定值,于是查找TabLayout中设置宽度的属性,但找来找去,有tabIndicatorHeight属性,却没有tabIndicatorWidth宽度的属性,莫非...

mahongy的博客 1732

python后端的支付宝小程序用户认证问题(alipay-sdk-python、pycrypto无法安装)

python后端的支付宝小程序用户认证问题(alipay-sdk-python、pycrypto无法安装) 写在前面 事先说明,本人不是大佬,我只是在不断探索的途中找到了解决这个问题的方法,之前在网上搜索的时候没有看到相关文章,所以就来简单讲一下。 正文 借着蚂蚁金服小程序大赛开通了支付宝小程序个人开发者,尝试将一个微信小程序的项目移植到支付宝上,支付宝对于用户唯一id的获取比微信要复杂很多,微信...

weixin_43102379的博客 3648

[Android]Tablayout:修改指示器indicator的宽度

一、问题描述: 最近接触到了Tablayout,需求是要把Tablayout的下划线宽度缩短,或者说使其可以进行自定宽度。 百度上面大多数利用反射,(具体可百度查询),这种方法确实可以把下划线变短,但是同时也会缩短Tab的点击区域,并且过于短后会影响Tab上TextView的UI显示效果。总之,治标不治本,不是我想要的结果。 二、分析源码: 通过查询资料以及对TabLayout的源码进行分...

Ekko的博客 7689

【Unity动画系统】详解Root Motion动画在Unity中的应用(一)

什么时候勾选Bake into pose,当不希望动画带动游戏对象旋转时。在旋转的动画中一般是不用勾选的,因为就需要用它来带动我们的角色对象旋转。但在比如前进、后退、待机等动画来说,我们就可以勾选这里,以避免因动画文件本身的瑕疵而给我们带来的旋转。loop match:代表了这个动画在角度上的吻合度。如果这个动画在播放中转角过大,那么就会显示红色,告诉我们如果勾选bake into pose,则会带来不好的效果。

weixin_60154963的博客 6817

深入Android构建系统:一次修改ro.vendor.build.fingerprint失败的排查与解决记录

本文深入探讨了Android构建系统中修改ro.vendor.build.fingerprint的完整解决方案。通过分析vendor分区的特殊地位和构建指纹的生成路径,提供了三种实战修改方法,并揭示了指纹修改可能遇到的陷阱与对策,帮助开发者彻底解决这一常见问题。

weixin_30621711的博客 165

[Android] TabLayout设置下划线(Indicator)宽度

在使用TabLayout的过程中,为每个标签添加一个 下划线,但发现每个下划线的 宽度 都是一样的,例如会如下显示 这样很难看,所以必须进行调整后的效果如下: 看,这样不是非常和谐啦!~~ 实现方法很简单,只需要用反射重写一些 TabLayout 就行! 我这里干脆做成了一个Util类TabLayoutUtil .java ,代码如下: package com....

weixin_30670151的博客 688

PCIe Link Training 深度解析:从物理检测到高速数据传输

本文深入解析PCIe链路训练(Link Training)的技术细节,揭示了这一复杂协商过程的五个关键阶段:物理检测阶段通过电气特性识别设备连接;轮询阶段建立时钟和符号同步;配置阶段确定链路宽度并处理拓扑异常;恢复阶段完成速率切换和信号均衡;最终进入正常工作状态。文章特别强调了高速率下的均衡技术挑战,以及验证工程师需要关注的多个维度,包括状态机跳转、有序集内容、均衡算法和错误恢复能力。随着PCIe速率不断提升,理解这一底层机制对高速接口设计具有重要价值。

元直的博客 1674

TabLayout设置下划线(Indicator)宽度

再战TabLayout之下划线宽度 这周的需求搞定之后,想到之前有一个小瑕疵,反正没什么事,索性较量较量 如图官方原版就是小瑕疵,反射版本就是最终 解决方案-Demo源码 先讲解决方案。直接贴代码(要在tabLayout添加完所有的tab后调用) [java] view plain copy publicvoidreflex(fina...

b13197741196的博客 333

YOLOv8【第十章:多任务扩展深度篇·第16节】车道线检测——基于 YOLOv8-Seg 的车道线分割与拟合!

🏆 本文收录于 《YOLOv8实战:从入门到深度优化》 专栏。该专栏系统复现并梳理全网各类 YOLOv8 改进与实战案例(当前已覆盖分类 / 检测 / 分割 / 追踪 / 关键点 / OBB 检测等方向),坚持持续更新 + 深度解析,质量分长期稳定在 97 分以上,可视为当前市面上 覆盖较全、更新较快、实战导向极强 的 YOLO 改进系列内容之一。

**My Coding Family** 1万+

Unity之OpenXR+XR Interaction Toolkit实现 Gaze眼部追踪

在虚拟现实(VR)和增强现实(AR)应用中,眼动追踪是一项强大而受欢迎的技术。它可以让开发者更好地理解用户的注意力和行为,并创造出更加沉浸和智能的体验。在本文中,我们将探讨如何使用 Unity OpenXR 实现Gaze眼部追踪功能。

TxNet 1761

Android完全自定义下划线的TabLayout

一 介绍: 导航功能几乎是所有的APP都具备的基础功能之一,Android系统提供了TabLayout+ViewPager的组合来实现该功能。再使用之初,发现该组合真是无敌了,但是。。。总有一些UI设计师觉得原生TabLayout的下划线样式不符合用户的审美,比如说,下划线的宽度要跟文本的宽度一样,下划线的样式要换成图片等等。TabLayout在这些需求面前显得那么无助,程序员被迫搬砖。 WeTa...

那个人_的博客 1800

开源模型应用落地-qwen模型小试-入门篇(二)

在windows环境下,使用transformer设置模型参数/System Prompt/历史对话

以微薄之力,予他人些许温暖. 3260
上一篇: Android 7.0以上(包含8.0), popupWindow弹窗位置异常, 解决方案
下一篇: RecyclerView加载多布局界面上移(抢占焦点)
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值