我有一个带有嵌套 View V 的自定义布局,如下所示: LinearLayout L1 ---> LinearLayout L2 ---> View V.
我有一个为 V 注册的 OnTouchListener。在触摸事件中,我需要获取触摸事件相对于 View V 边缘的坐标。
event.getX() 和event.getY() 返回的值是相对于什么?我四处搜索并看到相互矛盾的陈述,有人说这些值已经相对于 View V 的边缘,但其他人说我需要从 event.getX() 和 event.getY() 中减去 View V 的边缘坐标以获得相对值坐标。
感谢您的帮助。
最佳答案
来自谷歌的文档
getX()方法:
The visual x position of this view, in pixels. This is equivalent to the translationX property plus the current left property.
setTranslationX()方法:
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()方法:
Left position of this view relative to its parent.
因此,getX() 返回 View 相对于其父 View 的水平位置。
更新:
对于event.getX()
,你得到的结果也是相对于父级的。
您可以通过在水平居中的 RelativeLayout 中放置一个按钮来进行简单测试,并在单击按钮时检查值
在您的布局 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>
在您的 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;
}
});
如果您单击其左边距的按钮,您将获得接近 0.0 的值。
关于Android:对于嵌套 View ,getX() 和gety() 相对于什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10854871/