美文网首页功能专区Android开发Android进阶之旅
TabLayout两种方式自定义指示器长度

TabLayout两种方式自定义指示器长度

作者: 蓅哖伊人为谁笑 | 来源:发表于2017-09-28 10:40 被阅读360次

    一直以来谷歌 design包都没有对tablayout指示器长度可变做兼容,本人研究源码得出两种解决方法

    1.复制Tablayout的源码,对其中绘制指示器的代码做修改

    2.利用反射

    下面上图

    复制源码修改绘制指示器的代码段

    @Override

    public void draw(Canvas canvas) {

    super.draw(canvas);

    // Thick colored underline below the current selection

    if(mIndicatorLeft>=0&&mIndicatorRight>mIndicatorLeft) {

    canvas.drawRect(mIndicatorLeft+ getTabMargin(), getHeight() -mSelectedIndicatorHeight,

    mIndicatorRight- getTabMargin(), getHeight(),mSelectedIndicatorPaint);

    }

    源生的绘制指示器已经对 指示器高度做了兼容,始终没有对长度做兼容,遂顺着谷歌的思路在draw这个方法里,将绘制指示器起始终点位置减去左右padding即可

    反射修改每个item的宽度

    默认情况下,每个tab栏的weight都是1,那么指示器也就是从0到1这么长,但是我们改变每个tab的左右margin,也能够让指示器绘制起始终止位置改变,但这种方式有个问题,指示器宽度不能小于文字宽度,否则文字显示不全。

    try{

    Field mTabStrip =tableLayout.getClass().getDeclaredField("mTabStrip");

    mTabStrip.setAccessible(true);

    LinearLayout ltab = (LinearLayout) mTabStrip.get(tableLayout);

    intchildCount = ltab.getChildCount();

    for(inti =0; i < childCount; i++) {

    View childAt = ltab.getChildAt(i);

    LinearLayout.LayoutParams params =newLinearLayout.LayoutParams(0, -1);

    params.weight=1;

    params.leftMargin=20;

    params.rightMargin=20;

    childAt.setLayoutParams(params);

    childAt.invalidate();

    }

    }catch(NoSuchFieldException e) {

    e.printStackTrace();

    }catch(IllegalAccessException e) {

    e.printStackTrace();

    }

    下面奉献上源代码,传送门:https://github.com/mrme2014/MaterialTabLayout

    相关文章

      网友评论

        本文标题:TabLayout两种方式自定义指示器长度

        本文链接:https://www.haomeiwen.com/subject/mpzcsxtx.html