【发布时间】:2011-08-26 11:05:47
【问题描述】:
我在 Android 上工作了一段时间,想知道是否可以在 android 中检索按钮的位置。
我的目标是获取 X 和 Y 坐标并将它们打印在 LOGCAT 上。
一些例子来告诉我如何将不胜感激。
谢谢
【问题讨论】:
我在 Android 上工作了一段时间,想知道是否可以在 android 中检索按钮的位置。
我的目标是获取 X 和 Y 坐标并将它们打印在 LOGCAT 上。
一些例子来告诉我如何将不胜感激。
谢谢
【问题讨论】:
当然,您可以获得这些,请确保在尝试获得位置之前至少绘制一次视图。您可以尝试获取 onResume() 中的职位并尝试这些功能
view.getLocationInWindow()
or
view.getLocationOnScreen()
或者如果你需要一些相对于父母的东西,使用
view.getLeft(), view.getTop()
API 定义的链接:
【讨论】:
就像Azlam 说你可以使用View.getLocationInWindow() 来获取坐标x,y。
这是一个例子:
Button button = (Button) findViewById(R.id.yourButtonId);
Point point = getPointOfView(button);
Log.d(TAG, "view point x,y (" + point.x + ", " + point.y + ")");
private Point getPointOfView(View view) {
int[] location = new int[2];
view.getLocationInWindow(location);
return new Point(location[0], location[1]);
}
奖励 - 获取给定视图的中心点:
Point centerPoint = getCenterPointOfView(button);
Log.d(TAG, "view center point x,y (" + centerPoint.x + ", " + centerPoint.y + ")");
private Point getCenterPointOfView(View view) {
int[] location = new int[2];
view.getLocationInWindow(location);
int x = location[0] + view.getWidth() / 2;
int y = location[1] + view.getHeight() / 2;
return new Point(x, y);
}
我希望这个例子仍然对某人有用。
【讨论】:
buttonObj.getX();
buttonObj.getY();
【讨论】: