Android自定义控件实现导航条IndicatorView

本文介绍了如何在Android中实现一个自定义控件,即导航条IndicatorView。该控件具备响应左右滑动、快速滑动、不同选择状态样式以及自动滚动至选项完全显示等功能。通过Scroller和VelocityTracker来处理滚动和快速滑动的交互。
摘要由CSDN通过智能技术生成

先上效果图,DEMO在最下面



这个控件其实算是比较轻量级的,相信不少小伙伴都能做出来。因为项目中遇到了一些特殊的定制要求,所以就自己写了一个,这里放出来。

首先来分析下这个控件的功能:

  • 能够响应左右滑动,并且能响应快速滑动
  • 选择项和未选择项有不同的样式表现,比如前景色,背景色,字体大小变粗之内的
  • 在切换选项的时候,如果当前选项未完全呈现在界面前,则自动滚动直至当前选项完全暴露显示
前两条还有,简简单单就实现了,主要是第三点,这才是我自定义这个控件的原因!那么如果要实现这个控件,需要用到哪些知识呢?
  • 用Scroller来实现控件的滚动
  • 用VelocityTracker来实现控件的快速滚动

如果上面两种技术你都已经会了,那么我们就可以开始讲解代码了。首先是一些属性的Getter/Setter方法,这里采用的链式设置法:
    public IndicatorView color(int colorDefault, int colorSelected, int colorBg){
        this.colorDefault = colorDefault;
        this.colorSelected = colorSelected;
        this.colorBg = colorBg;
        return this;
    }

    public IndicatorView textSize(int textSize){
        this.textSize = textSize;
        return this;
    }

    public IndicatorView text(String[] texts){
        this.texts = texts;
        return this;
    }

    public IndicatorView padding(int[] padding){
        this.padding = padding;
        return this;
    }

    public IndicatorView defaultSelect(int defaultSelect){
        this.selectItem = defaultSelect;
        return this;
    }

    public IndicatorView lineHeight(int lineHeight){
        this.lineHeight = lineHeight;
        return this;
    }

    public IndicatorView listener(OnIndicatorChangedListener listener){
        this.listener = listener;
        return this;
    }

    public IndicatorView type(Type type){
        this.type = type;
        return this;
    }

这里我们将每一个选项抽象成了一个Item类:
    public class Item {
        String text;
        int colorDefault;
        int colorSelected;
        int textSize;
        boolean isSelected = false;
        int width;
        Point drawPoint;
        int[] padding = new int[4];
        Rect rect = new Rect();
    }

然后是控件的初始化操作,主要根据当前控件的宽高,以及设置的一些属性,进行Item选项的初始化:
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
        width = MeasureSpec.getS
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值