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

Viewed 22460

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?

4 Answers

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.

I found a way to not need the raw coordinates.

getX() and getY() should return you coordinates relative to the View that dispatched them.

It's correct. But in general we want coordinates relative to container View, not dispatched view.

float xRelativeToParent = view.getX() + motionEvent.getX();
float yRelativeToParent = view.getY() + motionEvent.getY();

Then, to move the center of the touched view to a moving pointer position, do:

view.setX(xRelativeToParent - view.getWidth()/2f);
view.setY(yRelativeToParent - view.getHeight()/2f);
Related