自定义View -简单的 SwitchView

简介: 前言实现一个简单的滑动开发,效果图如下:switchView完整版本分析平分整个View为两份平分VIew测量字体的高度和宽度,确定左右View的文字的位置并进行绘制确定字体的位置和绘制绘制...

前言

实现一个简单的滑动开发,效果图如下:

img_8bd352f363505b3d3f857d6ce377993d.gif
switchView完整版本

分析

  1. 平分整个View为两份
img_31d27c125b210bc13851988ab7c27ce6.png
平分VIew
  1. 测量字体的高度和宽度,确定左右View的文字的位置并进行绘制
img_816feea56bd9523aa3b2d6e6cf508475.png
确定字体的位置和绘制
  1. 绘制背景颜色,如果有圆角,绘制==圆角 #f44336==

  2. 在文字下层绘制一个==背景View(矩形) #ff5722==,有圆角的情况下会绘制圆角

img_dfbf5c693b1e5b8758fda5ec24efd827.png
绘制背景View
  1. 设置点击事件,在点击事件中开启一个 ==ValueAnimator.ofFloa(1) #f44336== 动画, 在==onDraw() #f44336==不断的通过动画的执行==百分比 #f44336== 计算背景View的X轴坐标进行绘制。

6 动画完成保存状态和设置文字的颜色。

编码

确定属性

首先确定需要哪一些属性,然后在慢慢的对属性进行实现。

<declare-styleable name="SwitchView">
    <!--关闭文字-->
    <attr name="off_text" format="string" />
    <!--打开文字-->
    <attr name="on_text" format="string" />
    <!--打开文字颜色-->
    <attr name="on_text_color" format="color" />
    <!--关闭文字颜色-->
    <attr name="off_text_color" format="color" />
    <!--无状态下的背景颜色-->
    <attr name="background_color" format="color" />
    <!--打开的背景颜色-->
    <attr name="on_background_color" format="color" />
    <!--关闭的背景颜色-->
    <attr name="off_background_color" format="color" />
    <!--字体大小-->
    <attr name="text_size" format="dimension" />
    <!--圆角-->
    <attr name="radius" format="dimension" />
</declare-styleable>

创建SwitchView

==SwitchView #f44336== 使用的完全接手 ==onDraw #f44336== ,自行进行相关绘制的自定义方式,所以我们需要继承至 ==View #f44336==

public class SwitchView extends View{
    public SwitchView(Context context) {
        this(context, null);
    }

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

    public SwitchView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initAttr(context, attrs);
    }

    private void initAttr(Context context, AttributeSet attrs) {
        
    }
}

初始化相关属性

/**
 * 初始化属性
 *
 * @param context 上下午
 * @param attrs 属性
 */
private void initAttr(Context context, AttributeSet attrs) {
    TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.SwitchView);
    //关闭文字
    offText = typedArray.getString(R.styleable.SwitchView_off_text);
    offText = TextUtils.isEmpty(offText) ? "关闭" : offText;
    //打开文字
    onText = typedArray.getString(R.styleable.SwitchView_on_text);
    onText = TextUtils.isEmpty(onText) ? "打开" : onText;
    //关闭文字颜色
    offTextColor = typedArray.getColor(R.styleable.SwitchView_off_text_color, offTextColor);
    //打开文字颜色
    onTextColor = typedArray.getColor(R.styleable.SwitchView_on_text_color, onTextColor);
    //背景颜色
    mBackgroundColor = typedArray.getColor(R.styleable.SwitchView_background_color, mBackgroundColor);
    //打开背景颜色
    mOnBackgroundColor = typedArray.getColor(R.styleable.SwitchView_on_background_color, mOnBackgroundColor);
    //关闭背景颜色
    mOffBackgroundColor = typedArray.getColor(R.styleable.SwitchView_off_background_color, mOnBackgroundColor);
    //文字大小
    textSize = typedArray.getDimension(R.styleable.SwitchView_text_size, 16);
    //圆角
    mRadius = typedArray.getDimension(R.styleable.SwitchView_radius, mRadius);
    //前面那个按钮的长度
    mFrontGroundWidth = typedArray.getDimension(R.styleable.SwitchView_front_ground_width, 0);

    typedArray.recycle();
    //初始化画笔
    mPaint = new Paint();
    mPaint.setStrokeWidth(5);
    mPaint.setAntiAlias(true);
}

测量和计算

测量整个View的宽高,确定左右两部分的长度和文字的位置

protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);
    //View的宽度
    mWidth = w;
    //View的高度
    mHeight = h;
    //高度的中间
    mCenterHeight = h / 2;
    //宽度的中间
    mCenterWidth = w / 2;
    //创建背景矩形
    mBackgroundRectf = new RectF(0, 0, mWidth, mHeight);
    //打开的矩形
    mOnRectf = new RectF(0, 0, mCenterWidth, mHeight);
    //文字的中间高度
    Rect mRect = new Rect();
    mPaint.setTextSize(textSize);
    // 测量打开文字
    mPaint.getTextBounds(onText, 0, onText.length(), mRect);
    onTextCenterHeight = mRect.height() * 0.4f;
    //测量关闭文字
    mPaint.getTextBounds(offText, 0, offText.length(), mRect);
    offTextCenterHeight = mRect.height() * 0.4f;
}

绘制文字和背景

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    // 设置颜色
    mPaint.setColor(mBackgroundColor);
    ////绘制背景矩形
    canvas.drawRoundRect(mOnRectf, mRadius, mRadius, mPaint);

    //绘制打开文字
    mPaint.setColor(onTextColor);
    mPaint.setTextSize(textSize);
    canvas.drawText(onText, mCenterWidth / 2 - mPaint.measureText(onText) / 2, mCenterHeight + onTextCenterHeight, mPaint);


    //绘制关闭文字
    mPaint.setColor(offTextColor);
    mPaint.setTextSize(textSize);
    canvas.drawText(offText, (mCenterWidth + mCenterWidth / 2) - mPaint.measureText(offText) / 2, mCenterHeight + offTextCenterHeight, mPaint);

}

查看效果:

img_fcf0b73b6fedf34cc3cb4752725e89fc.png
背景效果

绘制打开背景

绘制开关颜色

mOnRectf = new RectF(0 , 0, width , mHeight);
mPaint.setColor(mOnBackgroundColor);
canvas.drawRoundRect(mOnRectf, mRadius, mRadius, mPaint);

img_41709999f3fe91687dfa982d3cea779e.png
打开预览

完善细节

基本上到这一步骤就已经是差不多了,现在需要做的是:

  • 响应点击事件,启动动画
  • 根据动画的执行值更改RectF的left的值,如果处于打开,那么left增加,关闭则left减少
  • 定义一个接口,动画完成回调结果。

点击事件和动画

 @Override
public void onClick(View v) {
    startAnim();
}

private void startAnim() {
    if (valueAnimator == null || !valueAnimator.isRunning()) {
        //发散一个宽度的值
        valueAnimator = ValueAnimator.ofFloat(1).setDuration(300);
        valueAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                aminValueHundred = (float) animation.getAnimatedValue();
                invalidate();
            }

        });
        isExchangeColor = false;
        valueAnimator.start();
    }
}

onDraw代码

protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    // 更改颜色
    mPaint.setColor(mBackgroundColor);
    // 绘制背景矩形
    canvas.drawRoundRect(mBackgroundRectf, mRadius, mRadius, mPaint);


    //当前百分比的宽度
    int valueWidth = (int) (mCenterWidth * aminValueHundred);
    if (isOn) {
        //打开
        mOnRectf = new RectF(0 + valueWidth, 0, mCenterWidth + valueWidth, mHeight);
        mPaint.setColor(mOnBackgroundColor);
        if (aminValueHundred >= 0.5 && !isExchangeColor) {
            ////置换两种颜色
            mTempTextColor = offTextColor;
            offTextColor = onTextColor;
            onTextColor = mTempTextColor;
            isExchangeColor = true;
        }
        if (aminValueHundred >= 0.5) {
            mPaint.setColor(mOffBackgroundColor);
        }
    } else {
        //关闭
        mOnRectf = new RectF(mCenterWidth - valueWidth, 0, mWidth - valueWidth, mHeight);
        mPaint.setColor(mOffBackgroundColor);
        if (aminValueHundred >= 0.5 && !isExchangeColor) {
            //置换两种颜色
            mTempTextColor = onTextColor;
            onTextColor = offTextColor;
            offTextColor = mTempTextColor;
            isExchangeColor = true;
        }
        if (aminValueHundred >= 0.5) {
            mPaint.setColor(mOnBackgroundColor);
        }
    }
    if (!isOn && aminValueHundred == 1 && valueAnimator == null) {
        mOnRectf = new RectF(valueWidth, 0, mWidth, mHeight);
        mPaint.setColor(mOffBackgroundColor);
    }

    canvas.drawRoundRect(mOnRectf, mRadius, mRadius, mPaint);

    //绘制打开文字
    mPaint.setColor(onTextColor);
    mPaint.setTextSize(textSize);
    canvas.drawText(onText, mCenterWidth / 2 - mPaint.measureText(onText) / 2, mCenterHeight + onTextCenterHeight, mPaint);


    //绘制关闭文字
    mPaint.setColor(offTextColor);
    mPaint.setTextSize(textSize);
    canvas.drawText(offText, (mCenterWidth + mCenterWidth / 2) - mPaint.measureText(offText) / 2, mCenterHeight + offTextCenterHeight, mPaint);
    // 动画结束
    if (aminValueHundred == 1 && valueAnimator != null) {
        valueAnimator = null;
        isOn = !isOn;
        if (onSwitchListener != null) {
            onSwitchListener.onSwitchListener(isOn, isOn ? onText : offText);
        }

    }
}

查看效果:


img_e40fa08c80d4f3916980e1916d3f73ff.gif
完成预览

最后

当前只是实现了一个简单的切换,更多背景的颜色切换并没有完成,还有一些细节,现在还是比较生硬,希望下一步能实现更细腻的动画,就像下面这个这样:

img_dfff76ddf2cad12b39246cf25289c9d2.png
switch button

未完待续、敬请期待!
我的博客地址
源码地址

img_1ee92a858822d3b1d90a45e40e7b1042.jpe
FullScreenDeveloper
目录
相关文章
|
小程序 安全 网络协议
Nginx配置小程序域名(HTTPS
Nginx配置小程序域名(HTTPS
Nginx配置小程序域名(HTTPS
|
机器学习/深度学习 算法 PyTorch
深度学习经典算法PPO的通俗理解
#1 前置知识点 基本概念 [https://www.yuque.com/docs/share/04b60c4c-90ec-49c7-8a47-0dae7d3c78c7?#](https://www.yuque.com/docs/share/04b60c4c-90ec-49c7-8a47-0dae7d3c78c7?#) (部分符合的定义在这里) 要理解PPO,就必须先理解Actor
10208 0
|
12月前
|
数据采集 机器学习/深度学习 算法框架/工具
Python:现代编程的瑞士军刀
Python:现代编程的瑞士军刀
547 104
|
8月前
|
人工智能 边缘计算 调度
智启未来:2026年,AI从“技术工具”到“共生文明”的跨代元年
2026年,“会基础设施”范式跃迁开启人类与非生物智能共治的“第二个起源”。AI从工具升维为文明要素:技术迈入工业级确定性应用,能力下沉至个体;产业全链重构,制度启动动态合规、权责厘清与红利再分配;文明契约转向生态共生、意义赋予与思维共同体培育——未来在制度与共识之中。
492 1
|
10月前
|
SQL 分布式计算 DataWorks
【跨国数仓迁移最佳实践7】基于 MaxCompute 多租的大数据平台架构
本系列文章将围绕东南亚头部科技集团的真实迁移历程展开,逐步拆解 BigQuery 迁移至 MaxCompute 过程中的关键挑战与技术创新。本篇为第七篇,基于MaxCompute 多租的大数据平台架构。 注:客户背景为东南亚头部科技集团,文中用 GoTerra 表示。
628 27
|
8月前
|
人工智能 自然语言处理 监控
2026年适合电商的BI产品推荐,让数据成为核心竞争力
2026年,电商竞争进入“微秒级决策”时代。瓴羊Quick BI凭借AI原生架构、电商专属基因与智能小Q助手,实现自然语言交互、自动洞察与预测分析,助力企业提升转化率、库存效率与营销ROI,让每位业务人员都成为数据分析师。(239字)
|
10月前
|
机器学习/深度学习 人工智能 缓存
面试官21问:深入剖析Transformer原理与测试工程!
本文整理了21个Transformer高频面试题,从测试开发视角解析其核心原理。通过理解多头注意力、位置编码等关键机制,帮助测试人员建立对大模型的可测试性认知,为设计AI系统验证方案打下基础。
|
10月前
|
Linux
openssl-1_0_0-1.0.2p-3.49.1.x86_64.rpm 怎么安装?CentOS/RHEL 手动安装RPM包详细步骤
openssl-1_0_0-1.0.2p-3.49.1.x86_64.rpm 是适用于CentOS/RHEL/Fedora等系统的64位OpenSSL 1.0.2p版本RPM安装包。通过rpm或yum命令安装,支持依赖处理与版本验证,适用于需特定OpenSSL版本的环境部署。(237字)
|
12月前
|
JavaScript 前端开发 开发者
Nest.js控制器深度解析:路由与请求处理的高级特性
以上就是对 NestJS 控制层高级特性深度解析:从基本概念到异步支持再到更复杂场景下拦截其与管道等功能性组件运用都有所涉及,希望能够帮助开发者更好地理解和运用 NestJS 进行高效开发工作。
554 15
|
人工智能 自然语言处理 算法
DeepSeek:国产AI新势力,普通人如何用它赚钱?
DeepSeek 是一款由中国团队开发的大型语言模型,以其强大的自然语言处理能力迅速崛起,成为ChatGPT等国外大模型的强劲对手。它支持智能写作、代码生成、内容创作等多种功能,广泛应用于自媒体、编程、商业分析等领域。DeepSeek不仅免费且部分开源,用户可以直接访问官网体验,无需科学上网。其长文本处理能力和编程辅助功能尤为突出,适合长文写作和代码优化。DeepSeek还提供了多种变现途径,如自媒体写作、AI编程服务、课程咨询等,帮助用户在AI时代创造额外收入。掌握DeepSeek,开启AI变现之旅! 注:关注微信公众号“飞川”,发送“deepseek”获取丰富的资料包。
1644 73