自定义Android Switch控件

本文介绍如何创建一个自定义的Android Switch控件,使其外观更美观。通过继承View类,实现关键方法如onMeasure(), onDraw()和onTouchEvent(),并利用png图片资源来实现动画效果。在触摸事件中,监听ACTION_DOWN, ACTION_MOVE, ACTION_UP和ACTION_CANCEL,确保当手指离开控件区域时,控件能正确响应。自定义Switch控件的难点在于处理ACTION_CANCEL事件,以防止圆点停留在中间不动的情况。最后,作者鼓励程序员要有钻研、细心和耐心的精神。" 125428667,8748992,解决Spring Boot项目启动报错:Cannot load driver class,"['java', 'spring boot', '数据库连接']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近要做一个自定义的android控件叫Switch。原生的switch大概使这个样子:
Android原生Switch
而我要做的自定义Switch大概是这个样子:
这里写图片描述
这样看起来,应该是自定义的要好看一点吧。

要实现这个效果,要写一个自定义View,继承自View类:

public class MySwitch extends View implements View.OnClickListener

其中最重要的是实现onMeasure()、onDraw()以及onTouchEvent()这两个方法。
onMeasure()是用来指定该自定义View的尺寸。
onDraw()方法是用来绘制这个View。
onTouchEvent()方法响应手指的按下、滑动、取消和抬起动作。
(具体的步骤在代码中,耐心看会看懂)
需要三张png格式的图片(图片可以右键存下来):
这里写图片描述
这里写图片描述
这里写图片描述
整体逻辑是这样的:
首先用Bitmap把这三张图片加载进来。
在onDraw()方法中将指定位置的特定图片绘制出来。
在onTouch()方法监听手指按下(ACTION_DOWN)、滑动(ACTION_MOVE)、抬起(ACTION_UP)以及取消(ACTION_CANCEL)。让图片的绘制位置跟随手指的特定动作,以实现动画效果。
至于具体如何实现的,看代码吧。
要着重说下取消(ACTION_CANCEL)。有可能在手指滑动过程中,出现手指滑出控件区域,这时抬起(ACTION_UP)时间并不会被响应。这时,可能会出现圆点停在中间不动的现象,所以务必加上取消(ACTION_CANCEL)的响应。

(感想:要成为程序员,要有钻研精神、细心、耐心。坚持就有回报!共勉)

package com.example.root.jayzhao;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

/**
 * Created by Jay Zhao on 16-1-20.
 */
public class MySwitch extends View implements View.OnClickListener {

    int index = 0;
    public MySwitch(Context context) {
        this(context, null);
        // TODO Auto-generated constructor stub
    }

    public MySwitch(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
        // TODO Auto-generated constructor stub
    }

    public MySwitch(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // TODO Auto-generated constructor stub
        init();
    }

    private Bitmap thumb, thumbEnable, track, thumbDisable;
    int maxMove;
    int move = 0;
    float current = 0;
    float first = 0;
    boolean switchOn  =true;
    Rect mDest, mSrc;
    public static Bitmap resizeImage(Bitmap bitmap, int w, int h) {
        Bitmap BitmapOrg = bitmap;
        int width = BitmapOrg.getWidth();
        int height = BitmapOrg.getHeight();
        int newWidth = w;
        int newHeight = h;

        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;

        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 0, 0, width,
                height, matrix, true);
        return resizedBitmap;
    }


    public void init() {
        thumbEnable = BitmapFactory.decodeResource(getResources(),
                R.drawable.switch_thumb_enable);

        track = BitmapFactory.decodeResource(getResources(),
                R.drawable.switch_track_enable);
        thumbDisable = BitmapFactory.decodeResource(getResources(),
                R.drawable.switch_thumb_disable);
        thumbEnable = resizeImage(thumbEnable, 50, 50);
        thumbDisable = resizeImage(thumbDisable, 50, 50);
        track =  resizeImage(track, 100, 50);
        thumb = thumbEnable;


        maxMove = track.getWidth() - thumb.getWidth();
        mSrc = new Rect(0, 0, thumb.getWidth(), thumb.getHeight());
        mDest = new Rect();


        setOnClickListener(this);
        setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                first = event.getX();
                break;
            case MotionEvent.ACTION_MOVE:
                current = event.getX();
                move = (int)(current - first);
                if((switchOn && move < 0)||(!switchOn && move > 0)) {
                    move = 0;
                }
                if(Math.abs(move) > maxMove) {
                    move = move > 0 ? maxMove : -maxMove;
                }
                invalidate();
                return true;
            case MotionEvent.ACTION_UP:
                if(move != 0 && Math.abs(move) < maxMove/2) {
                    move = 0;
                    invalidate();
                    return true;
                }
                else if(Math.abs(move) >= maxMove/2 && Math.abs(move) < maxMove) {
                    move = move > 0? maxMove:-maxMove;
                    if(switchOn) {
                        switchOn = false;
                        thumb = thumbDisable;
                    }
                    else {
                        switchOn = true;
                        thumb = thumbEnable;
                    }
                    move = 0;
                    invalidate();
                    return true;
                }
                return super.onTouchEvent(event);
            case MotionEvent.ACTION_CANCEL:
                if(move != 0 && Math.abs(move) < maxMove/2) {
                    move = 0;
                    invalidate();
                    return true;
                }
                else if(Math.abs(move) >= maxMove/2 && Math.abs(move) < maxMove) {
                    move = move > 0? maxMove:-maxMove;
                    if(switchOn) {
                        switchOn = false;
                        thumb = thumbDisable;
                    }
                    else {
                        switchOn = true;
                        thumb = thumbEnable;
                    }
                    move = 0;
                    invalidate();
                    return true;
                }
                return super.onTouchEvent(event);
        }
        invalidate();
        return super.onTouchEvent(event);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  //设置控件的尺寸
        // TODO Auto-generated method stub
        setMeasuredDimension(track.getWidth(), track.getHeight());
    }



    @Override
    protected void onDraw(Canvas canvas) {

        if(move > 0 || move == 0 && switchOn) {
            mDest.set(move, 0, move + thumb.getWidth(), thumb.getHeight());
        }
        else if(move < 0 || move == 0 && !switchOn){
            mDest.set(move + track.getWidth() - thumb.getWidth(), 0, move + track.getWidth(), thumb.getHeight());
        }

        canvas.drawBitmap(track, 0, 0, null);
        canvas.drawBitmap(thumb, mSrc, mDest, null);

        super.onDraw(canvas);
    }

    @Override
    public void onClick(View v) {
        //Log.d("Jay", "Clicked!!!+'" + ++index);
        if(switchOn) {
            switchOn = false;
            move = maxMove;
            thumb = thumbDisable;
        }
        else {
            switchOn = true;
            move = -maxMove;
            thumb = thumbEnable;
        }
        invalidate();
    }
}

xml文件:

<com.example.root.jayzhao.MySwitch 

android:layout_height="wrap_content" 

android:layout_width="wrap_content" 

android:id="@+id/wiperSwitch1" 

android:layout_gravity="center_vertical"/>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值