我已经在 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();