不到百行代码实现,类似iPhone的滑块开关

时间:2022-04-27
本文章向大家介绍不到百行代码实现,类似iPhone的滑块开关,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

自定义view写了这么多篇幅,通用的属性部分代码,测量代码忽略不计

真正实现的部分就不到100行!先上效果图

关闭状态

打开状态

动起来

下面我们看下我们的实现;

  • 绘制背景,绘制圆球
 @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawSwichBg(canvas);
        drawSwichBallByFlag(canvas);
    }
private void drawSwichBallByFlag(Canvas canvas) {
// 绘制滑动的小球
        canvas.drawCircle(swichBallx, strockRadio, solidRadio, viewBallPaint);
    }

    private void drawSwichBg(Canvas canvas) {
    // 绘制圆角背景
        canvas.drawRoundRect(bgStrockRectF, strockRadio, strockRadio, viewStrockPaint);
        canvas.drawRoundRect(bgRectF, solidRadio, solidRadio, viewBgPaint);
    }
  • 计算圆球的边界和移动范围
 @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        viewHeight = h;
        viewWidth = w;

//计算小球半径和圆角背景的矩形范围
        strockRadio = viewHeight / 2;
        solidRadio = (viewHeight - 2 * switchViewStrockWidth) / 2;

        swichBallx = strockRadio;
        bgStrockRectF = new RectF(0, 0, viewWidth, viewHeight);
        bgRectF = new RectF(switchViewStrockWidth, switchViewStrockWidth, viewWidth - switchViewStrockWidth, viewHeight - switchViewStrockWidth);
    }
 public void setOpenState(boolean openState) {
 //根据小球的开关状态,重置小球位置
        isOpen = openState;
        swichBallx = isOpen ? viewWidth - strockRadio : strockRadio;
        int currentStrockColor = isOpen ? switchViewBgOpenColor : switchViewStrockColor;
        int currentBgColor = isOpen ? switchViewBgOpenColor : switchViewBgCloseColor;
        viewStrockPaint.setColor(currentStrockColor);
        viewBgPaint.setColor(currentBgColor);
    }
  • 滑动处理
public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                break;
            case MotionEvent.ACTION_MOVE:
            // 小球跟随手指移动,并且限制边界范围
                int moveX = (int) event.getX();
                if (moveX < strockRadio) {
                    moveX = strockRadio;
                }
                if (moveX > viewWidth - strockRadio) {
                    moveX = viewWidth - strockRadio;
                }
                swichBallx = moveX;
                break;
            case MotionEvent.ACTION_UP:
            // 手指离开时,根据up的坐标设置view的开关状态
                int upX = (int) event.getX();
                if (upX > viewWidth / 2) {
                    setOpenState(true);
                } else {
                    setOpenState(false);
                }
                break;
        }
        invalidate();
        return true;
    }

核心代码结束,由于开关滑块比较小就没有加入弹性滑动以及属性动画 有兴趣的可以加一个valueanimion在UP中进行缓慢的滑动!

完整的代码和下载地址如下:

[https://github.com/GuoFeilong/ATDragViewDemo]

(https://github.com/GuoFeilong/ATDragViewDemo)