Search code examples
javaandroidtouch-event

How to locate a tap on the screen? X, Y cordinates


I'm trying to get the location (x, y in pixels) of a tap when tapping on the screen of the device. here is my code that i found:

@Override
public boolean onTouchEvent(MotionEvent event) {
    int x = (int)event.getX();
    int y = (int)event.getY();
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
        case MotionEvent.ACTION_MOVE:
        case MotionEvent.ACTION_UP:
    }
    System.out.println(x);
    System.out.println(y);
    return true;
}

But it does not fire the event. where is the problem?


Solution

  • System.out.println is for the classic, desktop console. Try using the Log output. It will be presented in LogCat. You can choose among different types of logs - verbose, info, debug, warn and error. Useful syntax may look like (although it's not following android's Log convention):

    String xstr = Integer.toString(x);
    Log.d("X location: ", xstr);
    

    Also take a look here to learn more about android logs.