如何获得按钮坐标? [英] How get Button coordinate?
本文介绍了如何获得按钮坐标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个布局activity_main.xml
:
I have a layout activity_main.xml
:
<Button
android:id="@+id/button"
android:layout_marginTop="50dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|top"
android:text="@string/hover"/>
</FrameLayout>
如何在屏幕上获取Button的坐标(x,y).现在我用:
How can i get Button's coordinate (x, y) on screen. for now I use:
button.getX()
button.getY()
但它是return 0.0
,我该如何实现.
谢谢
but it return 0.0
, How can i achieve this.
Thanks
推荐答案
之所以会发生这种情况,是因为在实际显示视图之前先获取其坐标.
This happens because you are getting the coordinates of your view before it's actually shown.
您可以使用View.post()
方法,该方法会在正确初始化View
后执行一些代码.
You can use the View.post()
method, which executes some code after your View
is properly initalized.
mButton.post(
new Runnable(){
@Override
public void run(){
x = mButton.getX();
y = mButton.getY();
}
}
);
这篇关于如何获得按钮坐标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文