Android canvas detect touch points

To detect the touch events on the canvas of a View class we can use the boolean method onTouchEvent(MotionEvent). In the View created in example below, it draws a line from previous touch point to new touch point.

public class SkView extends View{

private Paint myPaint;
float startX = 0;
float startY = 0;
float endX = 0;
float endY = 0;

public SkView(Context context){
super(context);
myPaint = new Paint();
}

@Override
protected void onDraw(Canvas canvas) {
myPaint.setStyle(android.graphics.Paint.Style.STROKE);
myPaint.setStrokeWidth(8);
myPaint.setColor(Color.RED);

canvas.drawLine(startX, startY, endX, endY, myPaint);

}

@Override
public boolean onTouchEvent(MotionEvent event) {
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
startX = endX;
startY = endY;
endX = event.getX();
endY = event.getY();
invalidate();
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}

}

This View can be added to a LinearLayout linear1 by writing linear1.addView(new SkView(this)); in onCreate event or any other event.