AKSHAY MANAGOOLI
AKSHAY MANAGOOLI

Reputation: 130

How to get Button's onscreen coordinates

I am trying to get coordinates of button, so that using that i wanna set position of dialog box at that button when clicked. i have placed button inside a LinearLayout(Which is parent layout for buttons), so i used below code to get coordinates

x = b1.getX();
y = b1.getY();

But above code gives coordinates respective with that LinearLayout, I want coordinates of button where it is situated in Main Parent layout. I searched for it i dint get proper answers, please help, Thanks in advance

Upvotes: 0

Views: 2450

Answers (2)

Abbas
Abbas

Reputation: 3331

Use method View.getLocationOnScreen(int[] location) like so,

int locations[] = new int[2];

view.getLocationOnScreen(locations);

locations[0] will have x-coordinate and location[1] y-coordinate.

Upvotes: 3

Robert Estivill
Robert Estivill

Reputation: 12477

Use View.getLocationOnScreen() and/or getLocationInWindow().

You can only invoke it AFTER layout has happened. You are calling the method before the views are positioned on screen

Upvotes: 1

Related Questions