怎么获取到View的位置View.getLocationInWindow()的为0

最近做项目时,发现在activity的onCreate()和onResume()方法里调用View.getLocationInWindow()时,View.getLocationInWindow()返回空值,觉得很奇怪,因为以前用过,没有发现这个问题,于是调查了一下源码,这里把调查结果做个记录。

首先,看看View.getLocationInWindow()的实现,

    public void getLocationInWindow(int[] location) {
        // When the view is not attached to a window, this method does not make sense
        if (mAttachInfo == null) return;
        ... ...
    }

这里有注释,说明当view没有绑定到window时,返回在window里的坐标是没有意义的。的确,窗口都没有,哪来的窗口坐标呀!!

       其次,看看view何时合适绑定到窗口。通过阅读源码,发现下面这段代码:

   void dispatchAttachedToWindow(AttachInfo info, int visibility) {
        //System.out.println("Attached! " + this);
        mAttachInfo = info;
        ... ...
   }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值