Reputation: 1246
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.
Upvotes: 3
Views: 6341
Reputation: 11568
From Google's documentation
getX() method:
The visual x position of this view, in pixels. This is equivalent to the translationX property plus the current left property.
setTranslationX() method:
Sets the horizontal location of this view relative to its left position. This effectively positions the object post-layout, in addition to wherever the object's layout placed it.
getLeft() method:
Left position of this view relative to its parent.
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:
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_centerHorizontal="true">
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</RelativeLayout>
In your activity:
mBtn = ((Button) findViewById( R.id.button1 ));
mBtn.setOnTouchListener( new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.d("", "getX = " + event.getX());
return false;
}
});
If you click the button on its left margin you will get a value close to 0.0.
Upvotes: 5