getGlobalVisibleRect、getLocalVisibleRect、getLocationInWindow、getLocationOnScreen

测试布局
在这里插入图片描述

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:id="@+id/linearlayout_test"
        android:layout_marginLeft="50px"
        android:layout_marginTop="50px"
        android:layout_width="200px"
        android:layout_height="200px"
        android:background="@color/colorPrimary"
        android:orientation="vertical"/>

</LinearLayout>

getGlobalVisibleRect()

这个方法会返回一个 View 是否可见的 boolean 值。以屏幕左上角为参考系,判断view是否有一部分仍然在屏幕中(没有被父View遮挡),则会返回true。反之,如果它全部被父View遮挡住或者本身就是不可见的,则会返回false

同时还会将该 View 的可见区域 left,top,right,bottom 值保存在一个rect对象中
在这里插入图片描述
该Rect是基于总整个屏幕的。若是普通activity,则 Rect 的 top 为可见的状态栏高度+可见的标题栏高度+ Rect 左上角到标题栏底部的距离

若是对话框式的 activity,则 y 坐标为 Rect 的 top 为可见的标题栏高度 + Rect 左上角到标题栏底部的距离,此时是无视状态栏的有无的

Rect rect = new Rect();
boolean b = linearLayout.getGlobalVisibleRect(rect);
if(b){
	Log.d("getGlobalVisibleRect",""+rect);
}

在这里插入图片描述

getLocalVisibleRect()

这个方法跟getGlobalVisibleRect用法相同,只不过是以 view 自身的左上角为参考系
在这里插入图片描述

以上方法在 OnCreate 方法中调用,都会返回 0,这是因为 View 还未加载完毕

getLocationInWindow()

一个控件在其父窗口中的坐标位置,获取在当前窗口内的绝对坐标
getLocationInWindow 是以B为原点的C的坐标
在这里插入图片描述
若是普通activity,则 y 坐标为可见的状态栏高度 + 可见的标题栏高度 + view左上角到标题栏底部的距离(可见的意思是:在隐藏了状态栏/标题栏的情况下,它们的高度以0计算)

若是对话框式的 activity,则 y 坐标为可见的标题栏高度 + view 到标题栏底部的距离,此时是无视状态栏的有无的

int[] location = new int[2];
linearLayout.getLocationInWindow(location);
int x = location[0];
int y = location[1];
Log.d("getLocationInWindow", "x:" + x + ",y:" + y);

在这里插入图片描述

getLocationOnScreen()

一个控件在其整个屏幕上的坐标位置,获取在整个屏幕内的绝对坐标,注意这个值是要从屏幕顶端算起,也就是包括了通知栏的高度

getLocationOnScreen以A为原点的C的坐标

在这里插入图片描述
注意
当view没有绑定到window时,返回在window里的坐标是没有意义的,以上4个方法如果在Activity的OnCreate()事件输出那些参数,是全为0,要等UI控件都加载完了才能获取到这些。所以可以在以下函数中调用这些方法

	@Override
    public void onWindowFocusChanged(boolean hasFocus) {
    ......
    }
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值