Retrieve the X & Y coordinates of a button in android?

∥☆過路亽.° 提交于 2019-12-18 04:48:12

问题


I've been working on Android for a while and would like to know if it is possible to retrieve the position of a button in android.

My target is to get the X & Y coordinates and print them on the LOGCAT.

Some example to show me how would be appreciated.

Thanks


回答1:


Sure, you can get these, make sure the views are drawn atleast once before you try to get the positions. You could try to get the positions in onResume() and try these functions

view.getLocationInWindow()
or
view.getLocationOnScreen()

or if you need something relative to the parent, use

view.getLeft(), view.getTop()

Links to API definitions:

  • getLocationInWindow
  • getLocationOnScreen
  • getLeft
  • getTop



回答2:


Like Azlam said you can use View.getLocationInWindow() to get the coordinates x,y.

Here is an example:

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]);
}

Bonus - To get the center point of the given view:

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);
}

I hope the example can still be useful to someone.




回答3:


buttonObj.getX();
buttonObj.getY();


来源:https://stackoverflow.com/questions/7203740/retrieve-the-x-y-coordinates-of-a-button-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!