Getting View's coordinates relative to the root layout

fhucho picture fhucho · Sep 1, 2010 · Viewed 162.1k times · Source

Can I get a View's x and y position relative to the root layout of my Activity in Android?

Answer

carlo.marinangeli picture carlo.marinangeli · Apr 20, 2016

The Android API already provides a method to achieve that. Try this:

Rect offsetViewBounds = new Rect();
//returns the visible bounds
childView.getDrawingRect(offsetViewBounds);
// calculates the relative coordinates to the parent
parentViewGroup.offsetDescendantRectToMyCoords(childView, offsetViewBounds); 

int relativeTop = offsetViewBounds.top;
int relativeLeft = offsetViewBounds.left;

Here is the doc