Reputation: 1673
I tried to make a simple custom view with TouchEvent. But if I click n drag the mouse cursor nothing is being drawn. Is this the way I should test TouchEvent on emulator ? Or I should run the app in real device (where it is also not working). Thanx
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;
}
}
Upvotes: 4
Views: 6075
Reputation: 2654
I tried this code in my emulator and it works, remember to keep the left button down while you move the mouse on the emulator view:
@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction() & MotionEvent.ACTION_MASK;
switch(action) {
case MotionEvent.ACTION_DOWN : {
path.moveTo(event.getX(), event.getY());
break;
}
case MotionEvent.ACTION_MOVE : {
path.lineTo(event.getX(), event.getY());
break;
}
}
invalidate();
return true;
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(path, myPaint);
}
private void init() {
myPaint = new Paint();
myPaint.setStyle(Paint.Style.STROKE);
myPaint.setColor(Color.CYAN);
}
Upvotes: 1