fhucho fhucho - 2 months ago 5x
Android Question

Getting View's coordinates relative to the root layout

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


This is one solution, though since APIs change over time and there may be other ways of doing it, make sure to check the other answers. One claims to be faster, and another claims to be easier.

private int getRelativeLeft(View myView) {
    if (myView.getParent() == myView.getRootView())
        return myView.getLeft();
        return myView.getLeft() + getRelativeLeft((View) myView.getParent());

private int getRelativeTop(View myView) {
    if (myView.getParent() == myView.getRootView())
        return myView.getTop();
        return myView.getTop() + getRelativeTop((View) myView.getParent());

Let me know if that works.

It should recursively just add the top and left positions from each parent container. You could also implement it with a Point if you wanted.