10

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

3 Answers3

14

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:

Hussein El Feky
  • 6,627
  • 5
  • 44
  • 57
Azlam
  • 2,052
  • 3
  • 24
  • 28
  • **getLocationInWindow(int[])** and **getLocationOnScreen(int[])** has parameter. Are you sure about your idea? – hakki Feb 19 '13 at 03:55
  • @hakkikonu take a look to my answer to understand the usage of **getLocationInWindow(int[])**. – Ryan Amaral Jun 01 '15 at 16:35
11

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.

Community
  • 1
  • 1
Ryan Amaral
  • 4,059
  • 1
  • 41
  • 39
2
buttonObj.getX();
buttonObj.getY();
Lalit kumar
  • 2,377
  • 1
  • 22
  • 17