我所理解的是,getLocationOnScreen返回的位置增加了状态栏(或动作栏或标题栏)的高度。在Y轴上,从屏幕左上角开始。
getLocationInWindow返回从活动的根内容视图左上角开始的位置。
现在,一切似乎都说得通了。但当我尝试使用getLocationOnScreen和getLocationInWindow获取位置时,它们都返回相同的按钮位置,并增加了状态栏的高度。对于getLocationOnScreen来说,这似乎是正确的,但对于getLocationInWindow来说,这似乎是错误的。
我是不是漏掉了什么?或者它只是个buggy?我在API-4和API-14中对此进行了测试。
发布于 2017-11-29 11:33:07
尽管这个问题以前已经得到了回答,但我认为仍然值得努力让这个问题变得更清楚。
如果你研究一下getLocationOnScreen和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)
...
}下图进一步解释了这一点,其中蓝色表示屏幕,红色表示窗口:

需要注意的是,窗口可以是顶级窗口(覆盖整个屏幕),也可以是其他自定义窗口,如对话框。
所以,回到你的问题上:
getLocationOnScreen返回增加了状态栏高度的位置
没错。您的电话屏幕包括状态栏的视图
getLocationOnScreen和getLocationInWindow,它们都返回相同的按钮位置,但增加了状态栏的高度
这是因为您正在处理的窗口是覆盖整个手机屏幕的顶层窗口。
发布于 2014-01-29 18:58:06
这个问题已经在这里被问到了:getLocationOnScreen() vs getLocationInWindow(),尽管被接受的答案是不正确的,正如@groucho所说的那样。
我可以抄袭他的答案,但我认为你最好在那里检查一下!
https://stackoverflow.com/questions/20138099
复制相似问题