154

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

Jonik
  • 80,077
  • 70
  • 264
  • 372
fhucho
  • 34,062
  • 40
  • 136
  • 186

11 Answers11

214

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

carlo.marinangeli
  • 2,958
  • 2
  • 17
  • 17
  • 21
    This should be the accepted answer. No possibility of a stack overflow, and no possibility of math errors. Thanks! – GLee Jul 29 '16 at 20:47
  • I agree, this should be the accepted answer -- only 92 up-votes to go. – dazed Aug 24 '17 at 10:18
  • I wanted to find the coordinates of a view in the toolbar. This is the one method that works consistently to account for android:fitsSystemWindows and various API versions from 19 to 27. So thank you! This IS the right answer. – David Ferrand Feb 22 '18 at 18:50
  • Worked flawlessly – Rawa Apr 30 '18 at 10:51
  • 3
    Worked very well, just want to mention that `parentViewGroup` can be any parent in the view hierarchy, so it works perfectly for ScrollView as well. – Sira Lam May 25 '18 at 07:33
  • You are a fu^&*(g godsend. Thank you! – Kedar Paranjape Aug 03 '18 at 14:05
  • I noticed that I get the same coordinates from this whether the view has been translated or not. This screwed up a calculation because it didn't account for the view being translated.Have you run into issues like that before? – AdamMc331 Jun 21 '19 at 19:37
  • 1
    This does not work: offsetTop is always zero on my device. I used view .getParent() for parentViewGroup – neoexpert Feb 24 '20 at 10:50
  • I always get 0. Please help. – user1090751 Oct 14 '20 at 11:33
  • Man, this is SWWEEEEEEET!!! Thank you! For those getting zero, make sure your ViewGroup is a direct parent of the view you need to acquire the relative coordinates for. – ONE Nov 22 '20 at 02:35
  • This is actual answer of above question, Thanks man – Ashish Jan 24 '21 at 12:15
  • Yeah, this provides a more accurate coordinate values – kc ochibili Dec 20 '22 at 21:38
148

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();
    else
        return myView.getLeft() + getRelativeLeft((View) myView.getParent());
}

private int getRelativeTop(View myView) {
    if (myView.getParent() == myView.getRootView())
        return myView.getTop();
    else
        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.

ramblinjan
  • 6,578
  • 3
  • 30
  • 38
  • getRelativeLeft() this is need add cast,but when i add (View) or (button) ((Object) myView.getParent()).getRelativeTop(),it is also not right – pengwang Sep 02 '10 at 07:11
  • I did something very similar but i checked for the root view by getId == R.id.myRootView. – fhucho Sep 02 '10 at 12:44
  • 1
    Log.i("RelativeLeft", ""+getRelativeLeft(findViewById(R.id.tv))); Log.i("RelativeTop", ""+getRelativeTop(findViewById(R.id.tv))); i get all is 0; textView in layout is as follows – pengwang Sep 03 '10 at 09:30
  • Smiliar approach like this (calculating it manually) worked for me so I accepted this answer. – fhucho May 05 '12 at 10:47
  • There is a chance that has something to do with the variable you're passing in. – ramblinjan May 22 '12 at 22:42
  • `getParent` return's a `ViewGroup` not a `View` so no idea how this worked for you... – Graeme Jul 10 '12 at 12:36
  • @Graeme propose an edit if it needs a cast or another method. – ramblinjan Jul 10 '12 at 15:53
  • It doesn't need a cast or another method - AFAIK you can't find a View's position through recursion through the hierarchy of view's... The correct answer is "View.getLocationInWindow()` – Graeme Jul 11 '12 at 08:20
  • Interesting, this returned the same results for me as getLocationOnScreen() which also returned the same as getLocationInWindow(). Nonetheless, you can specify a parent in the argument to end the recursion, aka, get the xy relative to a parent – Clocker Oct 23 '15 at 20:47
  • 3
    the android api already provides the relative coordinate to the root. look here http://stackoverflow.com/a/36740277/2008214 – carlo.marinangeli Aug 01 '16 at 10:29
  • 1
    Every time i am getting return value 0 from both method.I have a one TextView inside RelativeLayout. – Rohit Bandil Aug 09 '16 at 11:34
  • I got the solution, call both method form onWindowFocusChanged(boolean hasFocus) Activity class method.I think both method will only work when your Activity is visible to the user. – Rohit Bandil Aug 09 '16 at 12:06
  • OR change the method signature to use your own rootView if you want to get the left,top corner relative to a given parent view. I.E. `private int getRelativeLeft(View myView, View rootView) { if (myView.getParent() == rootView)` – Danuofr Sep 20 '16 at 21:33
  • I always get 0. Please help. – user1090751 Oct 14 '20 at 11:34
98

Please use view.getLocationOnScreen(int[] location); (see Javadocs). The answer is in the integer array (x = location[0] and y = location[1]).

Jonik
  • 80,077
  • 70
  • 264
  • 372
BinaryTofu
  • 1,167
  • 7
  • 7
  • 14
    This returns position rlative to the screen not to the root layout of Activity. – fhucho May 05 '12 at 10:44
  • 11
    There is also View.getLocationInWindow(int[]) which returns the view's position relative to the window. – Rubicon May 28 '12 at 18:57
  • Can you please tell me exactly how this method work. It returns a void how to do we get the output or x, y values of a view on the screen – user1106888 Nov 15 '12 at 22:24
  • 6
    To get the position relative to the root layout, just call getLocationInWindow for the root layout and the element, and use the power of subtraction. It's far simpler and likely faster than the accepted answer. – Blake Miller Apr 05 '13 at 08:06
  • I think this is a really useful answer, though maybe it could be edited to give viewers of this question an easy way to get the answer they're looking for. – ramblinjan Nov 15 '13 at 20:08
  • This is a crazy old post, but don't capitalize View because getLocationInWindow is not a static method – Chris Sprague Oct 30 '14 at 21:53
  • Both getLocationOnScreen and getGlobalVisibleRect include the status bar height. – Rupert Rawnsley Dec 15 '15 at 09:50
  • 1
    this is just the location related to the screen. not the the root. read here for relative to root: http://stackoverflow.com/a/36740277/2008214 – carlo.marinangeli Aug 01 '16 at 10:26
  • what is the view is scaled and rotated? – DKV Jan 02 '17 at 10:08
  • Be aware that the location on screen may work when the app is running full screen on an Android device, but will be different if your app is running in a window on Chrome OS. This may not be the desired location measurement. – Jeff Lockhart Feb 05 '20 at 21:21
41
View rootLayout = view.getRootView().findViewById(android.R.id.content);

int[] viewLocation = new int[2]; 
view.getLocationInWindow(viewLocation);

int[] rootLocation = new int[2];
rootLayout.getLocationInWindow(rootLocation);

int relativeLeft = viewLocation[0] - rootLocation[0];
int relativeTop  = viewLocation[1] - rootLocation[1];

First I get the root layout then calculate the coordinates difference with the view.
You can also use the getLocationOnScreen() instead of getLocationInWindow().

Kerrmiter
  • 646
  • 7
  • 12
38

No need to calculate it manually.

Just use getGlobalVisibleRect like so:

Rect myViewRect = new Rect();
myView.getGlobalVisibleRect(myViewRect);
float x = myViewRect.left;
float y = myViewRect.top;

Also note that for the centre coordinates, rather than something like:

...
float two = (float) 2
float cx = myViewRect.left + myView.getWidth() / two;
float cy = myViewRect.top + myView.getHeight() / two;

You can just do:

float cx = myViewRect.exactCenterX();
float cy = myViewRect.exactCenterY();
Clint Deygoo
  • 261
  • 3
  • 10
TalL
  • 1,661
  • 16
  • 16
  • Looking at the android source all `getGlobalVisibleRect` does is `globalOffset.set(-mScrollX, -mScrollY);` so you could just get those values with `getScollX/Y` if you only need the relative coodinates. – Xander Jan 16 '13 at 20:45
  • 2
    This should be accepted answer. getLocationOnScreen works as well as getGlobalVisibleRect. But getGlobalVisibleRect provides a bit more information's and there is no need to work with raw arrays. I would therefore go with getGlobalVisibleRect. The usage is simple. Rect positionRect = new Rect(); view.getGlobablVisibleRect(positionRect); //x = positionRect.left //y = positionRect.top. cheers – JacksOnF1re Jun 01 '15 at 14:31
  • if some part of the child is outside which will not take into consideration in this case. how to solve such case? – DKV Jan 02 '17 at 10:14
  • Great answer! Thank you so much! – Rohit Kumar Aug 19 '19 at 16:52
  • Anyone, @JacksOnF1re can you please answer this? https://stackoverflow.com/questions/68868778/animate-progreessbar-when-it-reaches-to-the-specific-pointfrom-bottom-and-compl – Irfan Yaqub Aug 25 '21 at 06:40
8

You can use `

view.getLocationOnScreen(int[] location)

;` to get location of your view correctly.

But there is a catch if you use it before layout has been inflated you will get wrong position.

Solution to this problem is adding ViewTreeObserver like this :-

Declare globally the array to store x y position of your view

 int[] img_coordinates = new int[2];

and then add ViewTreeObserver on your parent layout to get callback for layout inflation and only then fetch position of view otherwise you will get wrong x y coordinates

  // set a global layout listener which will be called when the layout pass is completed and the view is drawn
            parentViewGroup.getViewTreeObserver().addOnGlobalLayoutListener(
                    new ViewTreeObserver.OnGlobalLayoutListener() {
                        public void onGlobalLayout() {
                            //Remove the listener before proceeding
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                                parentViewGroup.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                            } else {
                                parentViewGroup.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                            }

                            // measure your views here
                            fab.getLocationOnScreen(img_coordinates);
                        }
                    }
            );

and then use it like this

xposition = img_coordinates[0];
yposition =  img_coordinates[1];
Hitesh Sahu
  • 41,955
  • 17
  • 205
  • 154
4

I wrote myself two utility methods that seem to work in most conditions, handling scroll, translation and scaling, but not rotation. I did this after trying to use offsetDescendantRectToMyCoords() in the framework, which had inconsistent accuracy. It worked in some cases but gave wrong results in others.

"point" is a float array with two elements (the x & y coordinates), "ancestor" is a viewgroup somewhere above the "descendant" in the tree hierarchy.

First a method that goes from descendant coordinates to ancestor:

public static void transformToAncestor(float[] point, final View ancestor, final View descendant) {
    final float scrollX = descendant.getScrollX();
    final float scrollY = descendant.getScrollY();
    final float left = descendant.getLeft();
    final float top = descendant.getTop();
    final float px = descendant.getPivotX();
    final float py = descendant.getPivotY();
    final float tx = descendant.getTranslationX();
    final float ty = descendant.getTranslationY();
    final float sx = descendant.getScaleX();
    final float sy = descendant.getScaleY();

    point[0] = left + px + (point[0] - px) * sx + tx - scrollX;
    point[1] = top + py + (point[1] - py) * sy + ty - scrollY;

    ViewParent parent = descendant.getParent();
    if (descendant != ancestor && parent != ancestor && parent instanceof View) {
        transformToAncestor(point, ancestor, (View) parent);
    }
}

Next the inverse, from ancestor to descendant:

public static void transformToDescendant(float[] point, final View ancestor, final View descendant) {
    ViewParent parent = descendant.getParent();
    if (descendant != ancestor && parent != ancestor && parent instanceof View) {
        transformToDescendant(point, ancestor, (View) parent);
    }

    final float scrollX = descendant.getScrollX();
    final float scrollY = descendant.getScrollY();
    final float left = descendant.getLeft();
    final float top = descendant.getTop();
    final float px = descendant.getPivotX();
    final float py = descendant.getPivotY();
    final float tx = descendant.getTranslationX();
    final float ty = descendant.getTranslationY();
    final float sx = descendant.getScaleX();
    final float sy = descendant.getScaleY();

    point[0] = px + (point[0] + scrollX - left - tx - px) / sx;
    point[1] = py + (point[1] + scrollY - top - ty - py) / sy;
}
2

Incase someone is still trying to figure this out. This is how you get the center X and Y of the view.

    int pos[] = new int[2];
    view.getLocationOnScreen(pos);
    int centerX = pos[0] + view.getMeasuredWidth() / 2;
    int centerY = pos[1] + view.getMeasuredHeight() / 2;
Sheraz Ahmad Khilji
  • 8,300
  • 9
  • 52
  • 84
  • THis doesn't work in my case ... please look at the question if you can solve it. https://stackoverflow.com/questions/68868778/animate-progreessbar-when-it-reaches-to-the-specific-pointfrom-bottom-and-compl – Irfan Yaqub Aug 25 '21 at 06:43
1

I just found the answer here

It says: It is possible to retrieve the location of a view by invoking the methods getLeft() and getTop(). The former returns the left, or X, coordinate of the rectangle representing the view. The latter returns the top, or Y, coordinate of the rectangle representing the view. These methods both return the location of the view relative to its parent. For instance, when getLeft() returns 20, that means the view is located 20 pixels to the right of the left edge of its direct parent.

so use:

view.getLeft(); // to get the location of X from left to right
view.getRight()+; // to get the location of Y from right to left
donmj
  • 379
  • 7
  • 13
1

You can use the following the get the difference between parent and the view you interested in:

private int getRelativeTop(View view) {
    final View parent = (View) view.getParent();
    int[] parentLocation = new int[2];
    int[] viewLocation = new int[2];

    view.getLocationOnScreen(viewLocation);
    parent.getLocationOnScreen(parentLocation);

    return viewLocation[1] - parentLocation[1];
}

Dont forget to call it after the view is drawn:

 timeIndicator.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
        final int relativeTop = getRelativeTop(timeIndicator);
    });
mspapant
  • 1,860
  • 1
  • 22
  • 31
0

I think it's best if you define the parent you wish to check, and if you want the root, choose it.

For this, I've made a simple, general function:

fun getPositionRelativeToParent(view: View, parentToReach: View): Point {
    var currentView: View? = view.parent as View?
    val result = Point(view.left, view.top)
    while (true) {
        if (currentView == null || currentView == parentToReach)
            break
        result.set(result.x + currentView.left, result.y + currentView.top)
        currentView = currentView.parent as View?
    }
    return result
}

Note that you need to use it after the Views found where to be positioned.

Here's an example. Suppose you have 2 Views. One is deep inside, and the other is a child of a common parent. Both have the same size and need to be positioned, one on top of the other.

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val mainContainer = findViewById<View>(R.id.mainContainer)
        val viewToInspect = findViewById<View>(R.id.viewToInspect)
        val viewToMove = findViewById<View>(R.id.viewToMove)
        findViewById<View>(android.R.id.content).doOnPreDraw {
            val pos = getPositionRelativeToParent(viewToInspect, mainContainer)
            Log.d("AppLog", "getPositionRelativeToParent:$pos")
            viewToMove.updateLayoutParams<MarginLayoutParams> {
                leftMargin=pos.x
                topMargin=pos.y
            }
        }
    }
}

XML:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/mainContainer" android:layout_width="match_parent"
    android:layout_height="match_parent" tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent" android:layout_height="wrap_content"
        android:layout_margin="10dp" android:gravity="center_horizontal"
        android:orientation="vertical">

        <TextView
            android:layout_width="100dp" android:layout_height="100dp" android:gravity="center"
            android:text="1" />

        <TextView
            android:id="@+id/viewToInspect" android:layout_width="100dp" android:layout_height="100dp"
            android:background="#ff00ff00" android:gravity="center_horizontal" android:text="2"
            android:textColor="#00f" />

    </LinearLayout>

    <TextView
        android:id="@+id/viewToMove" android:layout_width="100dp" android:layout_height="100dp"
        android:background="#66ff0000" android:gravity="center" android:text="3"
        android:textColor="#0ff" />
</FrameLayout>

You can see that one View is on top of the other.

android developer
  • 114,585
  • 152
  • 739
  • 1,270