An Android onTouchEvent method example (View class)

If you need to write an Android onTouchEvent method inside a View class, here’s some example source code (boilerplate/skeleton code) that shows how to implement this method, including how to use the MotionEvent in the method, and how to get the x and y location of the touch event:

public boolean onTouchEvent(MotionEvent event) {

    int eventAction = event.getAction();
    // you may need the x/y location
    int x = (int)event.getX();
    int y = (int)event.getY();

    // put your code in here to handle the event
    switch (eventAction) {
        case MotionEvent.ACTION_DOWN:
        case MotionEvent.ACTION_UP:
        case MotionEvent.ACTION_MOVE:
    // tell the View to redraw the Canvas
    // tell the View that we handled the event
    return true;


I commented the code, and I think it shows the most common way this method is used, so I won’t bother to add any explanation here. I showed how to get the x and y location of the touch event because you’ll generally want to check to see where the event occurred.

So, in summary, if you wanted to see an example Android onTouchEvent method (in a View class), I hope this example is helpful.