简体   繁体   中英

Android: For a nested view, what are getX() and gety() relative to?

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM