我尝试使用 TouchEvent 制作一个简单的自定义视图。但是,如果我单击并拖动鼠标光标,则不会绘制任何内容。这是我应该在模拟器上测试 TouchEvent 的方式吗?或者我应该在真实设备上运行该应用程序(它也无法正常工作)。谢谢
public class TouchEventView extends View {
private Paint paint = new Paint();
private Path path = new Path();
public TouchEventView(Context context, AttributeSet attrs) {
super(context, attrs);
paint.setAntiAlias(true);
paint.setColor(Color.WHITE);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeWidth(5f);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(path, paint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float eventX = event.getX();
float eventY = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
path.moveTo(eventX, eventY);
return true;
case MotionEvent.ACTION_MOVE:
path.lineTo(eventX, eventY);
break;
case MotionEvent.ACTION_UP:
// nothing to do
break;
default:
return false;
}
// Schedules a repaint.
invalidate();
return true;
}
}