自定义View之SwitchView

工作(我)太(太)忙(懒) 太长时间没有写博客了,再不写今年一晃就要过去了,顺便也总结下今年工作的一些技术点吧。这篇先从一个简单的自定义控件开始吧 先看最终效果图:

image

这是一个性别选择的控件 本质上是一个Switch类似的控件 需要满足的需求点有:

  • 支持左右滑动选中
  • 支持左右点击选中
  • 支持按钮渐变色
  • 支持选中和未选中状态字体颜色的变化

由此得出所涉及的自定义View的技术点有:

  • View的触摸事件和滑动事件的处理
  • 颜色渐变的计算相关api的运用

接下就从最基本的代码开始:

//初始化
public class GenderSwitchView extends View {
     public GenderSwitchView(Context context) {
        this(context, null);
    }

    public GenderSwitchView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public GenderSwitchView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

}

初始逻辑


 private ShapeDrawable backgroundDrawable;
 private ShapeDrawable genderDrawable;
 private float mProgress;
 private int mTouchSlop;
    
 private void initView(Context context) {
        int testSize = SizeUtils.sp2px(16);
        //这里是将宽高根据ui 设计图计算写死
        height = SizeUtils.dp2px(45);
        width = SizeUtils.dp2px(200);
        //圆角角度
        int radiis = SizeUtils.dp2px(80);
        //获取系统识别最小的滑动距离
        mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
        //获取系统触发点击事件的时长
        mClickTimeout = ViewConfiguration.getPressedStateDuration() + ViewConfiguration.getTapTimeout();

        selectTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        selectTextPaint.setTextAlign(Paint.Align.CENTER);
        selectTextPaint.setTextSize(testSize);
        selectTextPaint.setColor(Color.WHITE);

        defaultTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        defaultTextPaint.setTextAlign(Paint.Align.CENTER);
        defaultTextPaint.setTextSize(testSize);
        defaultTextPaint.setColor(grayText);

        mProgressAnimator = new ValueAnimator();
        
        float[] outerRadii = {radiis, radiis, radiis, radiis, radiis, radiis, radiis, radiis};//外矩形 左上、右上、右下、左下的圆角半径
        RectF inset = new RectF(0, 0, 0, 0);//内矩形距外矩形,左上角x,y距离, 右下角x,y距离
        float[] innerRadii = {0, 0, 0, 0, 0, 0, 0, 0};//内矩形 圆角半径
        RoundRectShape roundRectShape = new RoundRectShape(outerRadii, inset, innerRadii);
        backgroundDrawable = new ShapeDrawable(roundRectShape);
        int back_color = ContextCompat.getColor(context, R.color.col_f3f3f3);
        backgroundDrawable.getPaint().setColor(back_color);
        backgroundDrawable.setBounds(0, 0, width, height);

        
        girlStartColor = ContextCompat.getColor(context, R.color.col_ff719e);
        girlEndColor = ContextCompat.getColor(context, R.color.col_ffae9b);

        boyStartColor = ContextCompat.getColor(context, R.color.col_55a8ff);
        boyEndColor = ContextCompat.getColor(context, R.color.col_8998ff);
        //渐变色计算类
        argbEvaluator = new ArgbEvaluator();

        RoundRectShape shape = new RoundRectShape(outerRadii, inset, innerRadii);
        linearGradient = new LinearGradient(0, 0, boundsWidth, height, girlStartColor, girlEndColor, Shader.TileMode.REPEAT);
        genderDrawable = new ShapeDrawable(shape);
        genderDrawable.getPaint().setShader(linearGradient);
        genderDrawable.getPaint().setStyle(Paint.Style.FILL);
        boundsWidth = width / 2;
        bundsX = (int) (mProgress * boundsWidth);
        bounds = new Rect(bundsX, 0, boundsWidth + bundsX, height);
        genderDrawable.setBounds(bounds); 
    }
image

其中这段代码创建的是最底层圆角矩形Drawable:

float[] outerRadii = {radiis, radiis, radiis, radiis, radiis, radiis, radiis, radiis};//外矩形 左上、右上、右下、左下的圆角半径
RectF inset = new RectF(0, 0, 0, 0);//内矩形距外矩形,左上角x,y距离, 右下角x,y距离
float[] innerRadii = {0, 0, 0, 0, 0, 0, 0, 0};//内矩形 圆角半径
RoundRectShape roundRectShape = new RoundRectShape(outerRadii, inset, innerRadii);
backgroundDrawable = new ShapeDrawable(roundRectShape);
int back_color = ContextCompat.getColor(context, R.color.col_f3f3f3);
backgroundDrawab
le.getPaint().setColor(back_color);
backgroundDrawable.setBounds(0, 0, width, height);
image

创建用于滑动的选择性别的Drawable,这个Drawable涉及渐变色 用到了LinearGradient相关api Android之Shader用法详细介绍

//女士Drawable 颜色范围
girlStartColor = ContextCompat.getColor(context, R.color.col_ff719e);
girlEndColor = ContextCompat.getColor(context, R.color.col_ffae9b);
//男士Drawable 颜色范围
boyStartColor = ContextCompat.getColor(context, R.color.col_55a8ff);
boyEndColor = ContextCompat.getColor(context, R.color.col_8998ff);
        
RoundRectShape shape = new RoundRectShape(outerRadii, inset, innerRadii);
//颜色渐变
linearGradient = new LinearGradient(0, 0, boundsWidth, height, girlStartColor, girlEndColor, Shader.TileMode.REPEAT);
genderDrawable = new ShapeDrawable(shape);
//设置颜色渐变
genderDrawable.getPaint().setShader(linearGradient);
genderDrawable.getPaint().setStyle(Paint.Style.FILL);
//Drawable 宽高 为背景的一半
boundsWidth = width / 2;
bundsX = (int) (mProgress * boundsWidth);
bounds = new Rect(bundsX, 0, boundsWidth + bundsX, height);
genderDrawable.setBounds(bounds);

然后调用onDraw 进行绘制 看看效果:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //这里因为是知道具体宽高 在初始化的时候已经计算出来 这里直接设置进去即可
        setMeasuredDimension(width, height);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    backgroundDrawable.draw(canvas);//先绘制背景Drawable
    genderDrawable.draw(canvas);//再绘制上面一层用于可滑动的Drawable         
}

效果:


image

到这里最基本的已经做完了 但是目前还不能滑动 所以要开始重写onTouchEvent进行处理 这个也是这个自定义View 的重点 另外在滑动过程中择性别的Drawable需要渐变颜色:

    float mStartX;
    float mStartY;
    float mLastX;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();
        float deltaX = event.getX() - mStartX;
        float deltaY = event.getY() - mStartY;
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                mStartX = event.getX();
                mStartY = event.getY();
                mLastX = mStartX;
                setPressed(true);
                break;
            case MotionEvent.ACTION_MOVE:
                float x = event.getX();
                //计算滑动的比例 boundsWidth为整个宽度的一半
                setProcess(getProgress() + (x - mLastX) / boundsWidth);
                //这里比较x轴方向的滑动 和y轴方向的滑动 如果y轴大于x轴方向的滑动 事件就不在往下传递
                if ((Math.abs(deltaX) > mTouchSlop / 2 || Math.abs(deltaY) > mTouchSlop / 2)) {
                    if (Math.abs(deltaY) > Math.abs(deltaX)) {
                        return false;
                    }
                }
                mLastX = x;
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                setPressed(false);
                //计算从手指触摸到手指抬起时的时间
                float time = event.getEventTime() - event.getDownTime();
                //如果x轴和y轴滑动距离小于系统所能识别的最小距离 切从手指按下到抬起时间 小于系统默认的点击事件触发的时间  整个行为将被视为触发点击事件
                if (Math.abs(deltaX) < mTouchSlop && Math.abs(deltaY) < mTouchSlop && time < mClickTimeout) {
                    //获取事件触发的x轴区域 主要用于区分是左边还是右边
                    float clickX = event.getX();

                    //如果是在左边
                    if (clickX > boundsWidth) {
                        if (mProgress == 1.0f) {
                            return false;
                        } else {
                            animateToState(true);
                        }
                    } else {
                        if (mProgress == 0.0f) {
                            return false;
                        } else {
                            animateToState(false);
                        }
                    }
                    return false;
                } else {
                    boolean nextStatus = getProgress() > 0.5f;
                    animateToState(nextStatus);
                }
                break;
        }
        return true;
    }

通过滑动的距离来计算性别选着Drawable的绘制范围 :

全局创建了一个mProgress 用于计算性别选择Drewable的绘制范围 和颜色渐变的过程 当mProgress =1时 在右边 mProgress=0时在左边

public void setProcess(float progress) {
        LogUtils.e("setProcess(GenderSwitchView.java:141)进度" + progress);
        float tp = progress;
        if (tp > 1) {
            tp = 1;
        } else if (tp < 0) {
            tp = 0;
        }
        updatePaintStyle(tp);
        this.mProgress = tp;
        bundsX = (int) (mProgress * boundsWidth);
        bounds.left = bundsX;
        bounds.right = boundsWidth + bundsX;
        genderDrawable.setBounds(bounds);
        invalidate();
    }

通过滑动距离来计算颜色的渐变 这里用到颜色范围计算的api ArgbEvaluator

private void updatePaintStyle(float tp) {
       int  startColor = (int) (argbEvaluator.evaluate(tp, girlStartColor, boyStartColor));
       int endColor = (int) (argbEvaluator.evaluate(tp, girlEndColor, boyEndColor));
       LinearGradient linearGradient = new LinearGradient(0, 0, boundsWidth, height, startColor, endColor, Shader.TileMode.REPEAT);
       //将计算好的 颜色范围 重新设置到Drawable
      genderDrawable.getPaint().setShader(linearGradient);

    }

使用ValueAnimator来处理点击事件的动画效果:

protected void animateToState(boolean checked) {
        float progress = mProgress;
        if (mProgressAnimator == null) {
            return;
        }
        if (mProgressAnimator.isRunning()) {
            mProgressAnimator.cancel();
            mProgressAnimator.removeAllUpdateListeners();
        }
        mProgressAnimator.setDuration(mAnimationDuration);
        if (checked) {
            //右边
            mProgressAnimator.setFloatValues(progress, 1f);
        } else {
            //左边
            mProgressAnimator.setFloatValues(progress, 0.0f);
        }
        mProgressAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mProgress = (float) animation.getAnimatedValue();
                //通过ValueAnimator 进度更新 Drawable 渐变色范围
                updatePaintStyle(mProgress);
                bundsX = (int) (mProgress * boundsWidth);
                bounds.left = bundsX;
                bounds.right = boundsWidth + bundsX;
                //更新性别选择Drawable的绘制范围
                genderDrawable.setBounds(bounds);
                //绘制
                postInvalidate();
            }
        });
        mProgressAnimator.start();
    }

到这里所有事件相关的工作都做完了 看看效果:


image

剩下就是一些其他细节需求 最外层的文字 和标示图片等 另外文字的绘制需要计算BaseLine也就是绘制基准线:

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        //计算图片绘制的 x,y
        drawBitmapX = SizeUtils.dp2px(22);
        int textMargin = SizeUtils.dp2px(5);
        drawBitmapY = (height - girlSign.getHeight()) / 2;
        
        String mText = "男士";
        Rect bounds = new Rect();
        //测量文字的宽度
        selectTextPaint.getTextBounds(mText, 0, mText.length(), bounds);
        //获取文字的高度
        int textHeight = bounds.height();
        //计算文字绘制的 x,y
        drawTextX = drawBitmapX + girlSign.getWidth() + textMargin + bounds.width() / 2;
        drawTextY = height / 2 + textHeight / 2;
    }

最后一同绘制 其中文字颜色的变化 和图标的变化全都集中在更新性别选择Drawable 颜色渐变函数中 处理 这里不再贴代码了:

   @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        backgroundDrawable.draw(canvas);
        genderDrawable.draw(canvas);
        canvas.drawBitmap(girlSign, drawBitmapX, drawBitmapY, bitmapPaint);
        canvas.drawBitmap(boySign, width / 2 + drawBitmapX, drawBitmapY, bitmapPaint);
        canvas.drawText("女士", drawTextX, drawTextY, selectTextPaint);
        canvas.drawText("男士", width / 2 + drawTextX, drawTextY, defaultTextPaint);
    }

最终效果:

image

总结:在所有的自定义SwitchView 基础上都少不少触摸事件的处理 所以掌握触摸事件的处理情况下 剩下的各种花样需求都万变不离其宗 最后给上完整源码地址SwitchView 希望可以帮助到更多的人

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

推荐阅读更多精彩内容