Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I know if a MotionEvent is relative or absolute?

Tags:

android

touch

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?

like image 887
PeyloW Avatar asked Sep 11 '09 13:09

PeyloW


3 Answers

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.

like image 52
Dimitar Dimitrov Avatar answered Sep 28 '22 06:09

Dimitar Dimitrov


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.

like image 45
PeyloW Avatar answered Sep 28 '22 07:09

PeyloW


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.

like image 38
dyerjo Avatar answered Sep 28 '22 07:09

dyerjo