You need to enable JavaScript to run this app. Android 使用getLocationInWindow()获取控件X/Y坐标返回0怎么解决?
优惠活动
大模型
产品
解决方案
定价
更多

Android 使用getLocationInWindow()获取控件X/Y坐标返回0怎么解决?

Android调用getLocationInWindow返回0的解决方案

问题原因

你拿到Y坐标为0是调用获取坐标方法的时机错误导致的:Android 中 View 的测量、布局流程是在 onCreate/onStart 这些基础生命周期回调执行完成后才会运行的,如果你在这些生命周期里直接调用 getLocationInWindow,此时 View 还没完成位置计算,拿到的结果自然是 0。
另外你注释里直接打印 test 数组输出的是数组的内存哈希值,不是数组内容,这属于Java数组的基础特性,和坐标获取逻辑无关。

可行解决方案

方案1:使用View的post方法(最通用,推荐)

通过post提交的Runnable会在View完成测量、布局后自动执行,不需要额外处理生命周期:

txtView = findViewById(R.id.txtView);
txtNewView = findViewById(R.id.txtNewView);

// 等View布局完成后再获取坐标
txtView.post(() -> {
    int[] test = new int[2];
    txtView.getLocationInWindow(test);
    int y = test[1];
    txtNewView.setText(String.valueOf(y));
});

方案2:在onWindowFocusChanged中执行(仅Activity适用)

当Activity获得窗口焦点时,所有View已经完成布局,可以直接获取坐标:

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    if (hasFocus) {
        int[] test = new int[2];
        txtView.getLocationInWindow(test);
        int y = test[1];
        txtNewView.setText(String.valueOf(y));
    }
}

方案3:使用OnGlobalLayoutListener监听布局完成

如果需要在布局动态变化时持续获取最新坐标,可以用这个监听:

txtView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        // 第一次执行后移除监听,避免重复回调
        txtView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        int[] test = new int[2];
        txtView.getLocationInWindow(test);
        int y = test[1];
        txtNewView.setText(String.valueOf(y));
    }
});

内容的提问来源于stack exchange,提问作者odoojs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 09:06:04