Android – Screen Touch Handling – MotionEvent Attributes

Do you need info about user touch on the screen? It is quite simple, in your Activity class you must override the method  public boolean onTouchEvent(MotionEvent event) and manage there the Event. You are probably interested in MotionEvent.ACTION_DOWN, MotionEvent.ACTION_UP or MotionEvent.ACTION_MOVE. The code should look like this:

@Override
public boolean onTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        // manage down press
    }
    else if (event.getAction() == MotionEvent.ACTION_MOVE) {
        // manage move
    }
    else {
        // manage any other MotionEvent
    }
    return super.onTouchEvent(event);
}

Between if statement’s brackets you must deal with the MotionEvents. You can use some of the following.

Do you need the screen location of the user touch? Try this:

int touchX = event.getX();
int touchY = event.getY();

Do you need the pressure of the screen touch to quantify the reaction in your application? Or maybe a way of measuring the pressed area? You can find them like this:

int touchPressure = event.getPressure();
int touchSize = event.getSize();

Do you need the time when the current action started (with ACTION_DOWN)? And probably the current time to compute the difference and interpret some long presses or complex move actions? Try this:

int touchInitialTime = event.getDownTime();
int touchCurrentTime = event.getEventTime();

4 comments

  1. it’s very helpful thank you so much for this, you ow me an app xD

Leave a Reply

You must be logged in to post a comment.