定制TabLayout指示器样式

相信大家平时都有这样的需求,要修改原生TabLayout指示器的宽度。网上大致的做法可以总结为以下几种:
1.通过反射获取textView,修改宽度,但是这样tab就无法根据内容显示宽度了;
2.通过Tab.setCustomView(),在自定义布局里加上下划线,选中时显示,未选中时隐藏,但是这样没有滑动效果,切换会显得很生硬;
等等。
这篇文章自定义指示器样式的思路很简单:隐藏原生的指示器,在TabLayout子类的onDraw()中重绘指示器样式。
1.自定义TabLayout子类:

public class CustomIndicatorTabLayout extends TabLayout {
    private CustomIndicator customIndicator;
    private boolean initDraw = true;

    public CustomIndicatorTabLayout(Context context) {
        this(context, null);
    }

    public CustomIndicatorTabLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomIndicatorTabLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        setSelectedTabIndicatorColor(Color.TRANSPARENT);

        addOnTabSelectedListener(new OnTabSelectedListener() {
            @Override
            public void onTabSelected(Tab tab) {
                int position = tab.getPosition();
                View content = CustomIndicatorTabLayout.this.getChildAt(0);
                if (content instanceof ViewGroup) {
                    ViewGroup vg = (ViewGroup) content;
                    if (position < vg.getChildCount()) {
                        View child = vg.getChildAt(position);
                        if (child.getWidth() == 0) return;
                        if (customIndicator != null)
                            customIndicator.onSelected(position, child, vg);
                    }
                }
            }

            @Override
            public void onTabUnselected(Tab tab) {
                int position = tab.getPosition();
                View content = CustomIndicatorTabLayout.this.getChildAt(0);
                if (content instanceof ViewGroup) {
                    ViewGroup vg = (ViewGroup) content;
                    if (position < vg.getChildCount()) {
                        View child = vg.getChildAt(position);
                        if (child.getWidth() == 0) return;
                        if (customIndicator != null)
                            customIndicator.onUnselected(position, child, vg);
                    }
                }
            }

            @Override
            public void onTabReselected(Tab tab) {
                int position = tab.getPosition();
                View content = CustomIndicatorTabLayout.this.getChildAt(0);
                if (content instanceof ViewGroup) {
                    ViewGroup vg = (ViewGroup) content;
                    if (position < vg.getChildCount()) {
                        View child = vg.getChildAt(position);
                        if (child.getWidth() == 0) return;
                        if (customIndicator != null)
                            customIndicator.onReselected(position, child, vg);
                    }
                }
            }
        });
    }

    public void setCustomIndicator(CustomIndicator customIndicator) {
        this.customIndicator = customIndicator;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (initDraw) {
            initDraw = false;
            int position = customIndicator == null ? 0 : customIndicator.defaultPosition();
            View content = CustomIndicatorTabLayout.this.getChildAt(0);
            if (content instanceof ViewGroup) {
                ViewGroup vg = (ViewGroup) content;
                if (position < vg.getChildCount()) {
                    View child = vg.getChildAt(position);
                    if (customIndicator != null)
                        customIndicator.onDefaultSelected(position, child, vg);
                }
            }
        }
        if (customIndicator != null)
            customIndicator.draw(canvas);
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(canvas);
        if (initDraw) {
            initDraw = false;
            int position = customIndicator == null ? 0 : customIndicator.defaultPosition();
            View content = CustomIndicatorTabLayout.this.getChildAt(0);
            if (content instanceof ViewGroup) {
                ViewGroup vg = (ViewGroup) content;
                if (position < vg.getChildCount()) {
                    View child = vg.getChildAt(position);
                    if (customIndicator != null)
                        customIndicator.onDefaultSelected(position, child, vg);
                }
            }
        }
        if (customIndicator != null)
            customIndicator.draw(canvas);
    }

    public interface CustomIndicator {
        void draw(Canvas canvas);

        void onSelected(int position, View selected, ViewGroup parent);

        void onDefaultSelected(int position, View selected, ViewGroup parent);

        void onUnselected(int position, View unselected, ViewGroup parent);

        void onReselected(int position, View unselected, ViewGroup parent);

        int defaultPosition();
    }
}

2.实现CustomIndicator接口,实现动画绘制:常用滑动效果CommonIndicator

public class CommonIndicator implements CustomIndicatorTabLayout.CustomIndicator {
    private UnderlineAnim underlineAnim;
    private CustomIndicatorTabLayout tabLayout;

    public CommonIndicator(final CustomIndicatorTabLayout tabLayout, int color, int lineWidth, int lineHeight, long duration) {
        this.tabLayout = tabLayout;
        underlineAnim = new UnderlineAnim(color, lineWidth, lineHeight, duration, new AnimListener() {
            @Override
            public void notifyInvalidate() {
                tabLayout.invalidate();
            }
        });
    }

    @Override
    public void draw(Canvas canvas) {
        underlineAnim.draw(tabLayout, canvas);
    }

    @Override
    public void onSelected(int position, View selected, ViewGroup parent) {
        underlineAnim.animChangeOffset(getTabIndicatorOffset(selected));
    }

    @Override
    public void onDefaultSelected(int position, View selected, ViewGroup parent) {
        underlineAnim.changeOffset(getTabIndicatorOffset(selected));
        tabLayout.invalidate();
    }

    @Override
    public void onUnselected(int position, View unselected, ViewGroup parent) {

    }

    @Override
    public void onReselected(int position, View unselected, ViewGroup parent) {

    }

    @Override
    public int defaultPosition() {
        return 1;
    }

    private int getTabIndicatorOffset(View view) {
        return view.getLeft() + (view.getWidth() - this.underlineAnim.getLineWidth() >> 1);
    }

    public class UnderlineAnim {
        private Paint mPaint;
        private int lineWidth;
        private int lineHeight;
        private long duration;
        private int offset = 0;
        private int paddingBottom;
        private int corner;
        private ValueAnimator animator;
        private ValueAnimator.AnimatorUpdateListener updateListener;

        public UnderlineAnim(int color, int lineWidth, int lineHeight, long duration, final AnimListener animListener) {
            this.lineWidth = lineWidth;
            this.lineHeight = lineHeight;
            this.duration = duration;
            this.mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
            this.mPaint.setColor(color);
            this.mPaint.setStyle(Paint.Style.FILL);
            this.updateListener = new ValueAnimator.AnimatorUpdateListener() {
                public void onAnimationUpdate(ValueAnimator animation) {
                    UnderlineAnim.this.offset = (Integer) animation.getAnimatedValue();
                    if (animListener != null) {
                        animListener.notifyInvalidate();
                    }

                }
            };
        }

        public void setCorner(int corner) {
            this.corner = corner;
        }

        public int getLineWidth() {
            return this.lineWidth;
        }

        public void setStartOffset(int offset) {
            this.offset = offset;
        }

        public void setPaddingBottom(int paddingBottom) {
            this.paddingBottom = paddingBottom;
        }

        public void setDuration(long duration) {
            this.duration = duration;
        }

        public void setLineWidth(int lineWidth) {
            this.lineWidth = lineWidth;
        }

        public void setLineHeight(int lineHeight) {
            this.lineHeight = lineHeight;
        }

        public void animChangeOffset(int targetPosition) {
            if (this.offset != targetPosition) {
                if (this.animator == null) {
                    this.animator = ValueAnimator.ofInt(new int[]{this.offset, targetPosition});
                    this.animator.setDuration(this.duration);
                    this.animator.setInterpolator(new LinearInterpolator());
                    this.animator.addUpdateListener(this.updateListener);
                } else {
                    this.animator.end();
                    this.animator.setIntValues(new int[]{this.offset, targetPosition});
                }

                this.animator.start();
            }

        }

        public void changeOffset(int targetPosition) {
            this.offset = targetPosition;
        }

        public void draw(View view, Canvas canvas) {
            if (this.corner > 0 && Build.VERSION.SDK_INT >= 21) {
                canvas.drawRoundRect((float) this.offset, (float) (view.getHeight() - this.paddingBottom - this.lineHeight), (float) (this.offset + this.lineWidth), (float) (view.getHeight() - this.paddingBottom), (float) this.corner, (float) this.corner, this.mPaint);
            } else {
                canvas.drawRect((float) this.offset, (float) (view.getHeight() - this.paddingBottom - this.lineHeight), (float) (this.offset + this.lineWidth), (float) (view.getHeight() - this.paddingBottom), this.mPaint);
            }
        }
    }

    public interface AnimListener {
        void notifyInvalidate();
    }
}

3.粘性滑动效果StickyIndicator

public class StickyIndicator implements CustomIndicatorTabLayout.CustomIndicator {
    private StickyIndicator.UnderlineAnim underlineAnim;
    private CustomIndicatorTabLayout tabLayout;

    public StickyIndicator(final CustomIndicatorTabLayout tabLayout, int color, int lineWidth, int lineHeight, long duration) {
        this.tabLayout = tabLayout;
        underlineAnim = new StickyIndicator.UnderlineAnim(color, lineWidth, lineHeight, duration, new StickyIndicator.AnimListener() {
            @Override
            public void notifyInvalidate() {
                tabLayout.invalidate();
            }
        });
    }

    public StickyIndicator(final CustomIndicatorTabLayout tabLayout, int[] gradientColor, int lineWidth, int lineHeight, long duration) {
        this.tabLayout = tabLayout;
        underlineAnim = new StickyIndicator.UnderlineAnim(gradientColor, lineWidth, lineHeight, duration, new StickyIndicator.AnimListener() {
            @Override
            public void notifyInvalidate() {
                tabLayout.invalidate();
            }
        });
    }

    public UnderlineAnim getUnderlineAnim() {
        return underlineAnim;
    }

    @Override
    public void draw(Canvas canvas) {
        underlineAnim.draw(tabLayout, canvas);
    }

    @Override
    public void onSelected(int position, View selected, ViewGroup parent) {
        underlineAnim.animChangeOffset(getTabIndicatorOffset(selected));
    }

    @Override
    public void onDefaultSelected(int position, View selected, ViewGroup parent) {
        underlineAnim.changeOffset(getTabIndicatorOffset(selected));
        tabLayout.invalidate();
    }

    @Override
    public void onUnselected(int position, View unselected, ViewGroup parent) {

    }

    @Override
    public void onReselected(int position, View unselected, ViewGroup parent) {

    }

    @Override
    public int defaultPosition() {
        return 1;
    }

    private int getTabIndicatorOffset(View view) {
        return view.getLeft() + (view.getWidth() - this.underlineAnim.getLineWidth() >> 1);
    }

    public class UnderlineAnim {
        private final int LEFT = 0;
        private final int RIGHT = 1;
        private int fixDirection = -1;
        private int maxStickyLength = 0;
        private Paint mPaint;
        private int lineWidth;
        private int lineHeight;
        private long duration;
        private int curPosition = 0;
        private int targetPosition;
        private int paddingBottom;
        private int corner;
        private int[] gradientColor;
        private ValueAnimator animator;
        private ValueAnimator.AnimatorUpdateListener updateListener;

        public UnderlineAnim(int color, int lineWidth, int lineHeight, long duration, final StickyIndicator.AnimListener animListener) {
            this.lineWidth = lineWidth;
            this.lineHeight = lineHeight;
            this.duration = duration;
            this.mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
            this.mPaint.setColor(color);
            this.mPaint.setStyle(Paint.Style.FILL);
            this.updateListener = new ValueAnimator.AnimatorUpdateListener() {
                public void onAnimationUpdate(ValueAnimator animation) {
                    UnderlineAnim.this.curPosition = (Integer) animation.getAnimatedValue();
                    if (animListener != null) {
                        animListener.notifyInvalidate();
                    }
                }
            };
        }

        public UnderlineAnim(int[] gradientColor, int lineWidth, int lineHeight, long duration, final StickyIndicator.AnimListener animListener) {
            this.lineWidth = lineWidth;
            this.lineHeight = lineHeight;
            this.duration = duration;
            this.gradientColor = gradientColor;
            this.mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
            this.mPaint.setStyle(Paint.Style.FILL);
            this.updateListener = new ValueAnimator.AnimatorUpdateListener() {
                public void onAnimationUpdate(ValueAnimator animation) {
                    UnderlineAnim.this.curPosition = (Integer) animation.getAnimatedValue();
                    if (animListener != null) {
                        animListener.notifyInvalidate();
                    }
                }
            };
        }

        public void setMaxStickyLength(int maxStickyLength) {
            this.maxStickyLength = maxStickyLength;
        }

        public void setCorner(int corner) {
            this.corner = corner;
        }

        public int getLineWidth() {
            return this.lineWidth;
        }

        public void setPaddingBottom(int paddingBottom) {
            this.paddingBottom = paddingBottom;
        }

        public void setDuration(long duration) {
            this.duration = duration;
        }

        public void setLineWidth(int lineWidth) {
            this.lineWidth = lineWidth;
        }

        public void setLineHeight(int lineHeight) {
            this.lineHeight = lineHeight;
        }

        public void animChangeOffset(int targetPosition) {
            this.targetPosition = targetPosition;
            if (this.curPosition != targetPosition) {

                if (targetPosition > curPosition)
                    fixDirection = RIGHT;
                else fixDirection = LEFT;

                if (this.animator == null) {
                    this.animator = ValueAnimator.ofInt(this.curPosition, targetPosition);
                    this.animator.setDuration(this.duration);
                    this.animator.setInterpolator(new LinearInterpolator());
                    this.animator.addUpdateListener(this.updateListener);
                } else {
                    this.animator.end();
                    this.animator.setIntValues(this.curPosition, targetPosition);
                }

                this.animator.start();
            } else fixDirection = -1;

        }

        public void changeOffset(int targetPosition) {
            this.curPosition = targetPosition;
            this.targetPosition = targetPosition;
        }

        public void draw(View view, Canvas canvas) {
            float y1 = (float) (view.getHeight() - this.paddingBottom - this.lineHeight);
            float y2 = (float) (view.getHeight() - this.paddingBottom);
            float x1 = 0;
            float x2 = 0;

            if (fixDirection == LEFT) {
                x1 = targetPosition;
                x2 = curPosition + lineWidth;
                if (maxStickyLength > lineWidth) {
                    float d = x2 - x1;
                    if (d > maxStickyLength) {
                        x1 = x2 - maxStickyLength;
                    }
                }
            } else if (fixDirection == RIGHT) {
                x2 = targetPosition + lineWidth;
                x1 = curPosition;
                if (maxStickyLength > lineWidth) {
                    float d = x2 - x1;
                    if (d > maxStickyLength) {
                        x2 = x1 + maxStickyLength;
                    }
                }
            } else {
                x1 = curPosition;
                x2 = curPosition + lineWidth;
            }

            if (gradientColor != null) {
                @SuppressLint("DrawAllocation")
                Shader mShaderRight = new LinearGradient(x1, y1, x2, y2, gradientColor, null, Shader.TileMode.CLAMP);
                mPaint.setShader(mShaderRight);
            }

            if (this.corner > 0 && Build.VERSION.SDK_INT >= 21) {
                canvas.drawRoundRect(x1, y1, x2, y2, (float) this.corner, (float) this.corner, this.mPaint);
            } else {
                canvas.drawRect(x1, y1, x2, y2, this.mPaint);
            }
        }
    }

    public interface AnimListener {
        void notifyInvalidate();
    }
}

4.使用方式:

public class CustomIndicatorTabLayoutActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custom_indicator_tab_layout);

        CustomIndicatorTabLayout tab_layout = findViewById(R.id.tab_layout);
        tab_layout.setCustomIndicator(new CommonIndicator(tab_layout, Color.RED, 80, 8, 300));
        setup(tab_layout);

        CustomIndicatorTabLayout tab_layout2 = findViewById(R.id.tab_layout2);
        StickyIndicator stickyIndicator = new StickyIndicator(tab_layout2, new int[]{Color.parseColor("#2674FF"), Color.parseColor("#26E1FF")}, 80, 8, 300);
        stickyIndicator.getUnderlineAnim().setCorner(10);
        stickyIndicator.getUnderlineAnim().setMaxStickyLength(200);
        tab_layout2.setCustomIndicator(stickyIndicator);
        setup(tab_layout2);
    }

    private void setup(CustomIndicatorTabLayout tab_layout) {
        tab_layout.addTab(tab_layout.newTab().setText("测试1"));
        tab_layout.addTab(tab_layout.newTab().setText("测--试2"));
        tab_layout.addTab(tab_layout.newTab().setText("测试------3"));
        tab_layout.addTab(tab_layout.newTab().setText("测试4"));
        tab_layout.addTab(tab_layout.newTab().setText("测-----------------试5"));
        tab_layout.addTab(tab_layout.newTab().setText("测试6"));
        tab_layout.addTab(tab_layout.newTab().setText("测试7"));
        tab_layout.addTab(tab_layout.newTab().setText("-----测试8"));
        tab_layout.addTab(tab_layout.newTab().setText("测试9"));
        tab_layout.addTab(tab_layout.newTab().setText("测--试--10"));

        tab_layout.getTabAt(1).select();
    }
}

我就不上传动图了(上传动图贼麻烦o(╥﹏╥)o),新建项目拷贝代码运行就能看到效果。可扩展性强,只需要实现CustomIndicator就能实现你自己的自定义效果啦!ヾ( ̄▽ ̄)ByeBye

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,294评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,493评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,790评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,595评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,718评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,906评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,053评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,797评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,250评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,570评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,711评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,388评论 4 332
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,018评论 3 316
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,796评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,023评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,461评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,595评论 2 350

推荐阅读更多精彩内容

  • 1、需求 TabLayout+Viewpager+Fragment,在tab中显示一个红点,用来标识是否有新消息未...
    陈晓松快点跑阅读 6,011评论 0 1
  • 一、简述 TabLayout是Android Support Design库的新控件,可以用来实现开源框架View...
    CQ_TYL阅读 1,646评论 0 5
  • 转载自:https://www.jianshu.com/p/2b2bb6be83a8 序 [图片上传失败...(i...
    在下陈小村阅读 3,876评论 0 8
  • 序 上图是简书Android端的主页Tab,在其他的App中Tab也是很常见的,它的实现方式也有很多:TabHos...
    积木Blocks阅读 165,439评论 109 326
  • 、出师不利(三)改 因为最近天气实在太冷了,西门又没有交取暖费,就被停了暖气,实在没有法子,只好在屋子里搭了个炉子...
    千葱阅读 181评论 0 0