Android Creating Custom Views Responding to Touch Events


Many custom views need to accept user interaction in the form of touch events. You can get access to touch events by overriding onTouchEvent. There are a number of actions you can filter out. The main ones are

  • ACTION_DOWN: This is triggered once when your finger first touches the view.
  • ACTION_MOVE: This is called every time your finger moves a little across the view. It gets called many times.
  • ACTION_UP: This is the last action to be called as you lift your finger off the screen.

You can add the following method to your view and then observe the log output when you touch and move your finger around your view.

public boolean onTouchEvent(MotionEvent event) {

    int x = (int) event.getX();
    int y = (int) event.getY();
    int action = event.getAction();

    switch (action) {
        case MotionEvent.ACTION_DOWN:
            Log.i("CustomView", "onTouchEvent: ACTION_DOWN: x = " + x + ", y = " + y);

        case MotionEvent.ACTION_MOVE:
            Log.i("CustomView", "onTouchEvent: ACTION_MOVE: x = " + x + ", y = " + y);

        case MotionEvent.ACTION_UP:
            Log.i("CustomView", "onTouchEvent: ACTION_UP: x = " + x + ", y = " + y);
    return true;

Further reading: