How to get the absolute coordinates of a view
Use View.getLocationOnScreen()
and/or getLocationInWindow()
.
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.)