如何获取Button的屏幕坐标

时间:2017-05-16 09:07:20

标签: android android-studio button coordinates android-button

我正在尝试获取按钮的坐标,以便使用我想在单击时在该按钮上设置对话框的位置。我已将按钮放在LinearLayout(这是按钮的父布局)中,所以我使用下面的代码来获取坐标

x = b1.getX();
y = b1.getY();

但是上面的代码给出了与LinearLayout相对应的坐标,我想要按钮的坐标,它位于Main Parent布局中。我搜索了它,我得到了正确的答案,请帮助,提前致谢

2 个答案:

答案 0 :(得分:3)

使用方法View.getLocationOnScreen(int[] location),如此,

int locations[] = new int[2];

view.getLocationOnScreen(locations);

locations [0]将具有x坐标和位置[1] y坐标。

答案 1 :(得分:1)

使用View.getLocationOnScreen()和/或getLocationInWindow()

您只能在布局发生后调用它。您在视图位于屏幕上之前调用方法

相关问题