开关
1、继承View
2、测量宽高,等于背景图片的宽高
3、绘制自己,背景+滑动块
4、处理触摸事件,让滑动块随手指移动
1、继承View public class ToggleButton extends View { public ToggleButton(Context context, AttributeSet attrs) { super(context, attrs); } } 2、测量宽高,等于背景图片的宽高 public class ToggleButton extends View { private Bitmap backgroundBitmap; private Bitmap slideBitmap; private int slideLeftPos;// 滑动块距离左边的距离 private int slideLeftPosMax; public ToggleButton(Context context, AttributeSet attrs) { super(context, attrs); // 初始化背景图片和滑动块图片 backgroundBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.toogle_background); slideBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.toogle_slidebg); slideLeftPosMax = backgroundBitmap.getWidth()-slideBitmap.getWidth();// 滑动块距离左边最大值 } // 测量 @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // 设置自己的宽高,把背景图片的宽高作为自己的宽高 setMeasuredDimension(backgroundBitmap.getWidth(), backgroundBitmap.getHeight()); } } 3、绘制自己,背景+滑动块 // 绘制 @Override protected void onDraw(Canvas canvas) { // 绘制背景图片 canvas.drawBitmap(backgroundBitmap, 0, 0, null); // 绘制滑动块 canvas.drawBitmap(slideBitmap, slideLeftPos, 0, null); } 4、处理触摸事件,让滑动块随手指移动 // 处理触摸事件 @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: downX = (int) event.getX(); break; case MotionEvent.ACTION_MOVE: int moveX = (int) event.getX(); // 计算手指移动的距离 int distanceX = moveX - downX; // 更新滑动块距离左边的距离 slideLeftPos += distanceX; // 限制滑动块距离左边的距离 if(slideLeftPos<0){ slideLeftPos = 0; }else if(slideLeftPos>slideLeftPosMax){ slideLeftPos = slideLeftPosMax; } // 每次移动后,需要把当前move的位置赋值给down downX = moveX; // 重新绘制控件 invalidate(); break; case MotionEvent.ACTION_UP: // 计算滑动块中间点的位置,与背景图片中间点进行比较 // 滑动块中间点的位置<背景图片中间点 ,应该画到最左边,否则画到最右边 if(slideLeftPos + slideBitmap.getWidth()/2<backgroundBitmap.getWidth()/2){ slideLeftPos = 0; }else{ slideLeftPos = slideLeftPosMax; } // 重新绘制控件 invalidate(); break; default: break; } return true;// 消费掉事件 }
时间: 2024-12-06 16:30:57