自定义滑动锁定

自定义滑动锁定_第1张图片

package com.example.template;


import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;


public class SlideView extends View {


private Paint paint;
private Rect rect;
int start;
private Bitmap bitmap;
private Bitmap bitmap1;
private Bitmap bitmap2;
private int cirTop;
private int cirLeft;
private int bitTop;
private int bitLeft;
private boolean isEnable = true;;
private OnSlideListener mListener;


public SlideView(Context context, AttributeSet attrs) {
super(context, attrs);
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setTextSize(41);
paint.setColor(Color.WHITE);
bitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.bg_enable);
bitmap1 = BitmapFactory.decodeResource(getResources(),
R.drawable.enable);
bitmap2 = BitmapFactory.decodeResource(getResources(),
R.drawable.bg_disable);
start = bitmap1.getWidth();
cirLeft = start / 2;
cirTop = bitmap.getHeight() / 2 + cirLeft;
bitTop = start;
bitLeft = start - bitmap.getHeight() / 2;
}


@SuppressLint("DrawAllocation")
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawBitmap(bitmap, bitLeft, bitTop, paint);
float i = start / 2 + bitmap.getWidth() - bitmap.getHeight();
if (cirLeft <= i && cirLeft >= start / 2) {
} else if (cirLeft > i) {
cirLeft = (int) i;
} else {
cirLeft = start / 2;
}
int j = start / 2;
RectF dst = new RectF(bitLeft, bitTop, cirLeft + j, bitmap2.getHeight()
+ start);
Rect res = new Rect(0, 0, cirLeft, bitmap2.getHeight() + start);
canvas.drawBitmap(bitmap2, res, dst, paint);
canvas.drawBitmap(bitmap1, cirLeft, cirTop, paint);
rect = new Rect(cirLeft, cirTop, bitmap1.getWidth() + cirLeft,
bitmap1.getHeight() + cirTop);
}


@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouchEvent(MotionEvent event) {
//判断是否划到头了
if (!isEnable) {
return true;
}
//判断手指点的位置有没有在滑块内
if (event.getAction() == MotionEvent.ACTION_DOWN) {
int touchX = (int) event.getX();
int touchY = (int) event.getY();
if (!rect.contains(touchX, touchY)) {
return false;
}
}
//没滑到头就松开手指,滑块自动退到起始位
if (event.getAction() == MotionEvent.ACTION_UP) {
int UpX = (int) event.getX();
if (UpX >= start + bitmap.getWidth() - bitmap.getHeight()) {
isEnable = false;
//滑到头,回调
mListener.onSlide(!isEnable);
} else {
cirLeft = start / 2;
invalidate();
}
}

if (event.getAction() == MotionEvent.ACTION_MOVE) {
cirLeft = (int) (event.getX() - bitmap1.getWidth() / 2);
invalidate();
}




return true;
}



interface OnSlideListener {
void onSlide(boolean isEnd);
}
public void setOnSlideListener(OnSlideListener l) {
mListener = l;
}
}


你可能感兴趣的:(自定义)