I have a custom layout with a nested view V like so:
LinearLayout L1 —> LinearLayout L2 —> View V.
I have an OnTouchListener registered for V. On a touch event, I need to get the coordinates of the touch event relative to the edges of view V.
What are the values returned by event.getX() and event.getY() relative to? I’ve googled around and am seeing conflicting statements, some say these values are already relative to view V’s edges, yet others say I need to subtract edge coordinates of view V from event.getX() and event.getY() to get relative coordinates.
Thanks for your help.
From Google’s documentation
getX() method:
setTranslationX() method:
getLeft() method:
Therefore, getX() returns the view’s horizontal position relative to its parent.
UPDATE:
For
event.getX()the result you get is also relative to the parent.You can do a simple test by placing a button inside a RelativeLayout which is horizontally centered and check the value when you click the button
In your layout xml:
In your activity:
If you click the button on its left margin you will get a value close to 0.0.