定制TabLayout指示器樣式

相信大家平時(shí)都有這樣的需求,要修改原生TabLayout指示器的寬度。網(wǎng)上大致的做法可以總結(jié)為以下幾種:
1.通過反射獲取textView,修改寬度,但是這樣tab就無法根據(jù)內(nèi)容顯示寬度了;
2.通過Tab.setCustomView(),在自定義布局里加上下劃線,選中時(shí)顯示,未選中時(shí)隱藏,但是這樣沒有滑動(dòng)效果,切換會(huì)顯得很生硬;
等等。
這篇文章自定義指示器樣式的思路很簡(jiǎn)單:隱藏原生的指示器,在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.實(shí)現(xiàn)CustomIndicator接口,實(shí)現(xiàn)動(dòng)畫繪制:常用滑動(dòng)效果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.粘性滑動(dòng)效果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("測(cè)試1"));
        tab_layout.addTab(tab_layout.newTab().setText("測(cè)--試2"));
        tab_layout.addTab(tab_layout.newTab().setText("測(cè)試------3"));
        tab_layout.addTab(tab_layout.newTab().setText("測(cè)試4"));
        tab_layout.addTab(tab_layout.newTab().setText("測(cè)-----------------試5"));
        tab_layout.addTab(tab_layout.newTab().setText("測(cè)試6"));
        tab_layout.addTab(tab_layout.newTab().setText("測(cè)試7"));
        tab_layout.addTab(tab_layout.newTab().setText("-----測(cè)試8"));
        tab_layout.addTab(tab_layout.newTab().setText("測(cè)試9"));
        tab_layout.addTab(tab_layout.newTab().setText("測(cè)--試--10"));

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

我就不上傳動(dòng)圖了(上傳動(dòng)圖賊麻煩o(╥﹏╥)o),新建項(xiàng)目拷貝代碼運(yùn)行就能看到效果??蓴U(kuò)展性強(qiáng),只需要實(shí)現(xiàn)CustomIndicator就能實(shí)現(xiàn)你自己的自定義效果啦!ヾ( ̄▽ ̄)ByeBye

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1、需求 TabLayout+Viewpager+Fragment,在tab中顯示一個(gè)紅點(diǎn),用來標(biāo)識(shí)是否有新消息未...
    陳曉松快點(diǎn)跑閱讀 6,164評(píng)論 0 1
  • 一、簡(jiǎn)述 TabLayout是Android Support Design庫(kù)的新控件,可以用來實(shí)現(xiàn)開源框架View...
    CQ_TYL閱讀 1,802評(píng)論 0 5
  • 轉(zhuǎn)載自:http://www.itdecent.cn/p/2b2bb6be83a8 序 [圖片上傳失敗...(i...
    在下陳小村閱讀 3,949評(píng)論 0 8
  • 序 上圖是簡(jiǎn)書Android端的主頁(yè)Tab,在其他的App中Tab也是很常見的,它的實(shí)現(xiàn)方式也有很多:TabHos...
    積木Blocks閱讀 165,973評(píng)論 109 326
  • 、出師不利(三)改 因?yàn)樽罱鞖鈱?shí)在太冷了,西門又沒有交取暖費(fèi),就被停了暖氣,實(shí)在沒有法子,只好在屋子里搭了個(gè)爐子...
    千蔥閱讀 243評(píng)論 0 0

友情鏈接更多精彩內(nèi)容