【问题标题】:Confusion between getLocationInWindow and getLocationOnScreengetLocationInWindow 和 getLocationOnScreen 之间的混淆
【发布时间】:2013-11-22 06:04:00
【问题描述】:

我的理解是,getLocationOnScreen 从屏幕角的左上角返回 Y 轴上增加了状态栏(或操作栏或标题栏?)高度的位置。

getLocationInWindow 从活动的根内容视图的左上角返回位置。

现在,一切似乎都说得通了。但是当我尝试使用getLocationOnScreengetLocationInWindow 获取位置时,它们都返回相同的按钮位置,并增加了状态栏的高度。对于getLocationOnScreen,它似乎是正确的,但对于getLocationInWindow,它似乎是错误的。

我有什么遗漏吗?还是它只是越野车?我在 API-4 和 API-14 中对此进行了测试。

【问题讨论】:

标签: android


【解决方案1】:

尽管这个问题以前已经回答过,但我认为仍然值得努力使这个问题更清楚。

如果你查看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) 
    ...
}

这在下图中进一步解释,其中蓝色表示屏幕,红色表示窗口:

需要注意的是,window 可以是您的顶级窗口(覆盖整个屏幕),也可以是其他自定义窗口,例如对话框。

那么,回到你的问题:

getLocationOnScreen 返回添加状态栏高度的位置

没错。您的手机屏幕包括状态栏的视图

getLocationOnScreen 和 getLocationInWindow,它们都返回按钮的相同位置,并增加了状态栏的高度

这是因为您正在使用的窗口是覆盖整个手机屏幕的顶级窗口。

【讨论】:

    【解决方案2】:

    此问题已在此处提出:getLocationOnScreen() vs getLocationInWindow() 尽管接受的答案不正确,如 @groucho 所述。

    我可以复制他的答案,但我认为如果你在那里检查它会更好!

    【讨论】:

    • 是的,我知道这一点,在发帖之前我进行了相当深入的搜索。我必须使用活动的根视图然后进行一些计算。 :)
    猜你喜欢
    • 2013-07-14
    • 2011-02-07
    • 2016-09-22
    • 2015-06-01
    • 2020-01-08
    • 2012-10-21
    • 2011-09-22
    • 2013-01-03
    • 2012-06-23
    相关资源
    最近更新 更多