I am implementing OnTouchListener
and am receiving MotionEvent objects. Some ACTION_MOVE
events reports absolute X/Y coordinates, while some reports relative coordinates.
How can I ask a MotionEvent
what kind of coordinates it currently represents?
You may want to use these for absolute coordinates (absolute, regarding the screen of the device):
MotionEvent.getRawX()
MotionEvent.getRawY()
The other methods, getX()
and getY()
, should return you coordinates relative to the View
that dispatched them.
This is a limitation on the Android platform.
MotionEvent
will sometimes return absolute X and Y coordinates relative to the view, and sometimes relative coordinates to the previous motion event.
An event sent as ACTION_DOWN
will always be absolute, all other events will vary. There is no way to ask the MotionEvent
for the current type of coordinates.
This means that in practice getX()
and getY()
are useless for many use cases, and you should base your application logic on getRawX()
and getRawY()
that is guaranteed to return absolute coordinates, relative to the device screen.
When using the MapView, I was able to get the relative X and Y coordinates by subtracting the View.getLeft() and View.getTop() of the Window's content view (Window.ID_ANDROID_CONTENT) from the MotionEvent.getRawX() and MotionEvent.getRawY(), respectively.
The solution is discussed here:
http://andmobidev.blogspot.com/2010/01/getting-relative-coordinates-from.html
This should work for determining relative X and Y coordinates in the main layout view.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With