Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusion between getLocationInWindow and getLocationOnScreen

Tags:

android

What I have understood is that getLocationOnScreen returns location with added height of status bar (or actionbar or title bar too ?) in Y axis from very top-left of screen corner.

And getLocationInWindow returns location from top-left of root content view of activity.

Now, everything seems to make sense. But when Im trying to get location using getLocationOnScreen and getLocationInWindow, they both return same location of a button with added height of status bar. For getLocationOnScreen it seems correct but for getLocationInWindow it seems wrong.

Is there something I'm missing ? or its just buggy ? I tested this in API-4 and API-14.

like image 522
xmen Avatar asked Dec 02 '25 12:12

xmen


1 Answers

Even though this question has been answered before, I think it is still worth an effort to make this clearer.

If you look into the code of getLocationOnScreen and getLocationInWindow:

public void getLocationOnScreen(int[] outLocation) {
    // It calls the getLocationInWindow
    getLocationInWindow(outLocation);

    // and adjust accordingly in case the window is not the top-level window 
    final AttachInfo info = mAttachInfo;
    if (info != null) {
        outLocation[0] += info.mWindowLeft; // refer image below
        outLocation[1] += info.mWindowTop; // refer image below
    }
}

public void getLocationInWindow(int[] outLocation) {
    // do my calculation here 
    // by traversing views contained in this window (in a single tree of views) 
    ...
}

This is further explained in the image below, where blue indicates screen & red indicates window:

enter image description here

It is important to note that window can be your top-level window (covers the entire screen), or other custom windows such as dialog.

So, going back to your questions:

getLocationOnScreen returns location with added height of status bar

That's right. Your phone's screen includes the status bar's view

getLocationOnScreen and getLocationInWindow, they both return same location of a button with added height of status bar

That is because the window you are working with is the top level window that covers your entire phone's screen.

like image 51
Arial Avatar answered Dec 05 '25 03:12

Arial



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!