How to get the absolute coordinates of a view
Solution 1:
Use View.getLocationOnScreen()
and/or getLocationInWindow()
.
Solution 2:
The accepted answer didn't actually tell how to get the location, so here is a little more detail. You pass in an int
array of length 2 and the values are replaced with the view's (x, y) coordinates (of the top, left corner).
int[] location = new int[2];
myView.getLocationOnScreen(location);
int x = location[0];
int y = location[1];
Notes
- Replacing
getLocationOnScreen
withgetLocationInWindow
should give the same results in most cases (see this answer). However, if you are in a smaller window like a Dialog or custom keyboard, then use you will need to choose which one better suits your needs. - You will get
(0,0)
if you call this method inonCreate
because the view has not been laid out yet. You can use aViewTreeObserver
to listen for when the layout is done and you can get the measured coordinates. (See this answer.)
Solution 3:
First you have to get the localVisible rectangle of the view
For eg:
Rect rectf = new Rect();
//For coordinates location relative to the parent
anyView.getLocalVisibleRect(rectf);
//For coordinates location relative to the screen/display
anyView.getGlobalVisibleRect(rectf);
Log.d("WIDTH :", String.valueOf(rectf.width()));
Log.d("HEIGHT :", String.valueOf(rectf.height()));
Log.d("left :", String.valueOf(rectf.left));
Log.d("right :", String.valueOf(rectf.right));
Log.d("top :", String.valueOf(rectf.top));
Log.d("bottom :", String.valueOf(rectf.bottom));
Hope this will help