You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取RelativeLayout中FAB在屏幕上的X、Y坐标?

正确获取FAB按钮在屏幕上的坐标

嘿,我来帮你搞定这个问题!你提到的getPointOfView其实不是Android SDK里获取View坐标的正确方法,这就是为什么你拿到的都是0啦。要获取FAB在屏幕上的准确坐标,关键得等View完成测量和布局之后再获取,不然View还没绘制到屏幕上,自然返回的是初始的0值。下面给你两种靠谱的实现方式:

方法一:使用View.post()

post()方法会把Runnable放到View的消息队列里,等View完成布局、绘制完成后再执行,这时候就能拿到正确的坐标了:

// 先获取你的FAB实例
FloatingActionButton fab = findViewById(R.id.your_fab_id);

fab.post(new Runnable() {
    @Override
    public void run() {
        int[] location = new int[2];
        // 获取相对于屏幕左上角的坐标(包含状态栏区域)
        fab.getLocationOnScreen(location);
        int screenX = location[0];
        int screenY = location[1];
        
        // 如果需要相对于应用窗口的坐标(不包含状态栏的话要看窗口布局),可以用这个:
        // fab.getLocationInWindow(location);
        // int windowX = location[0];
        // int windowY = location[1];
        
        // 这里就可以使用拿到的坐标啦
        Log.d("FAB坐标", "屏幕X:" + screenX + ",屏幕Y:" + screenY);
    }
});

方法二:使用ViewTreeObserver.OnGlobalLayoutListener

这个监听器会在View的布局发生变化(首次布局完成也会触发)时回调,适合需要监听布局变化的场景:

FloatingActionButton fab = findViewById(R.id.your_fab_id);
ViewTreeObserver observer = fab.getViewTreeObserver();

observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        // 记得移除监听器,避免重复触发
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            fab.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        } else {
            fab.getViewTreeObserver().removeGlobalOnLayoutListener(this);
        }
        
        int[] location = new int[2];
        fab.getLocationOnScreen(location);
        int screenX = location[0];
        int screenY = location[1];
        
        Log.d("FAB坐标", "屏幕X:" + screenX + ",屏幕Y:" + screenY);
    }
});

为什么之前返回0?

在onCreate()、onStart()这类生命周期方法里直接调用坐标获取方法时,View还没完成测量和布局流程,此时它的位置参数还没被计算出来,所以返回的是初始的0值。上面两种方法都能确保在View真正绘制到屏幕上之后再获取坐标,自然就能拿到正确的数值了。

内容的提问来源于stack exchange,提问作者Cyrus the Great

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 08:51:34