需求:
1.小球可以随着手指移动而移动,在移动完成后,不会调用该控件的点击事件。
2.点击控件不移动的话,就是点击事件,小球不会移动。
效果图.gif
自定义View绘制一个小球
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
paint.setColor(0xFFFF00FF);
canvas.drawCircle(currentX, currentY, radius, paint);
}
跟随手指的小球
@Override
public boolean onTouchEvent(MotionEvent event) {
currentX = event.getX();
currentY = event.getY();
invalidate();
return super.onTouchEvent(event);
}
我们随便点个位置,发现小球会直接在点的位置进行绘制,而不是跟着手指进行移动,于是,进行优化
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
startX = event.getX();
startY = event.getY();
break;
case MotionEvent.ACTION_MOVE:
float endX = event.getX();
float endY = event.getY();
if (Math.abs(startX - endX) > 8 || Math.abs(startY - endY) > 8) {
currentX = endX;
currentY = endY;
invalidate();
}
break;
case MotionEvent.ACTION_UP:
break;
}
return super.onTouchEvent(event);
}
小球随手指进行移动,小球可能超出了屏幕,因此进行判断:小球不能被手机屏幕的上,下,左,右遮盖
if ((Math.abs(startX - endX) > 8 || Math.abs(startY - endY) > 8)
&& (getWidth() > (endX + radius) && endX > radius)
&& (getHeight() > (endY + radius) && endY > radius)) {
currentX = endX;
currentY = endY;
invalidate();
}
我想要给该控件添加点击事件,结果发现无论是点击和滑动该控件,都会调用该控件的点击事件,我想要只有点击的时候会调用控件的点击事件,而小球随手指滑动的是否不会调用点击事件,进一步优化的结果
package hf.text.customizeview.drawable_bool;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class BallMovesWithFinger extends View {
private Paint paint;
private float currentX = 60;
private float currentY = 60;
private float radius = 60;
public BallMovesWithFinger(Context context) {
this(context, null);
}
public BallMovesWithFinger(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public BallMovesWithFinger(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
paint = new Paint();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
paint.setColor(0xFFFF00FF);
canvas.drawCircle(currentX, currentY, radius, paint);
}
float startX = 0f;
float startY = 0f;
boolean flag = false;
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
startX = event.getX();
startY = event.getY();
flag = false;
break;
case MotionEvent.ACTION_MOVE:
float endX = event.getX();
float endY = event.getY();
if ((Math.abs(startX - endX) > 8 || Math.abs(startY - endY) > 8)
&& (getWidth() > (endX + radius) && endX > radius)
&& (getHeight() > (endY + radius) && endY > radius)) {
currentX = endX;
currentY = endY;
invalidate();
flag = true;
return true;
}
break;
case MotionEvent.ACTION_UP:
if (flag) {
return true;
} else {
break;
}
}
return super.onTouchEvent(event);
}
}
网友评论