Reputation: 27105
I respond to touch events inside a custom View in onTouchEvent(MotionEvent event)
. I'm having trouble with an inconsistency in coordinates: event.getRaw(Y)
returns the Y coordinate of a touch including the status bar, but myView.getTop()
returns the Y coordinate of the top of the view excluding the status bar. I've resorted to the following hack to correct for the height of the status bar:
// Get the size of the visible window (which excludes the status bar)
Rect rect = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
// Get the coordinates of the touch event, subtracting the top margin
final int x = (int) event.getRawX();
final int y = (int) event.getRawY() - rect.top;
Is there a better solution?
Upvotes: 2
Views: 2327
Reputation: 22371
If you only care about the coordinate relative to your parent view (for instance, you want to always assume the top left of your view is 0,0), you can just use getX() and getY() instead of their raw equivalents.
Otherwise, Basically you're trying to take X/Y relative to the screen (getRawX, getRawY) and convert them to X/Y coordinates relative to the Window (status bar is not part of the window).
Your current solution will work, but as discussed elsewhere, getWindowVisibileDisplayFrame has been slightly broken in the past. A safer method might be to determine the view's location in the window, and then use the x/y coordinates relative to that view.
int[] coords = new int[2];
myView.getLocationInWindow(coords);
final int x = event.getRawX() - coords[0];
final int y = event.getRawY() - coords[1];
Upvotes: 4