(转载)Android:6种方式让你高效 & 正确地获取View的坐标位置

前言

获取 View 坐标在 Android 开发中非常常见。今天将详细给大家讲解 获取 View 坐标常用6种方式:

  1. getLeft()、getTop()、getRight()、getBottom()
  2. getX()、getY()、getRawX()、getRawY()
  3. getLocationOnScreen()
  4. getLocationInWindow()
  5. getGlobalVisibleRect()
  6. getLocalVisibleRect()

方式1:getLeft()、getTop()、getRight()、getBottom()

1. 应用场景

获得 View 相对 父View 的坐标

2. 使用

view.getLeft();
view.getTop();
view.getRight();
view.getBottom();

3. 具体描述

View的位置由4个顶点决定的(如下A、B、C、D)

                           View的顶点

4个顶点的位置描述分别由4个值决定:(请记住:View的位置是相对于父控件而言的

方式2:getX()、getY()、getRawX()、getRawY()

1. 应用场景

获得点击事件处 相对点击控件 & 屏幕的坐标

2. 使用

该方式是通过motionEvent获取的

motionEvent event;

event.getX();       
event.getY();

event.getRawX();    
event.getRawY();

3. 具体介绍

方式3:getLocationInWindow()

1. 应用场景

获取控件 相对 窗口Window 的位置

2. 具体使用

int[] location = new int[2];
view.getLocationInWindow(location);
int x = location[0]; // view距离window 左边的距离(即x轴方向)
int y = location[1]; // view距离window 顶边的距离(即y轴方向)

// 注:要在onWindowFocusChanged()里获取,即等window窗口发生变化后

3. 示意图

方式4:getLocationOnScreen()

1. 应用场景

获得 View 相对 屏幕 的绝对坐标

2. 使用

int[] location = new int[2];
view.getLocationOnScreen(location);
int x = location[0]; // view距离 屏幕左边的距离(即x轴方向)
int y = location[1]; // view距离 屏幕顶边的距离(即y轴方向)

// 注:要在view.post(Runable)里获取,即等布局变化后

3. 示意图

方式5:getGlobalVisibleRect()

1. 应用场景

View可见部分 相对于 屏幕的坐标。

2. 具体使用

Rect globalRect = new Rect();
view.getGlobalVisibleRect(globalRect);

globalRect.getLeft();
globalRect.getRight();
globalRect.getTop();
globalRect.getBottom();

3. 示意图

方式6:getLocalVisibleRect()

1. 应用场景

View可见部分 相对于 自身View位置左上角的坐标。

2. 具体使用

Rect localRect = new Rect();
view.getLocalVisibleRect(localRect);

localRect.getLeft();
localRect.getRight();
localRect.getTop();
localRect.getBottom();

3. 示意图

总结

本文对Android获取View坐标位置的方式进行了全面讲解,总结如下:

如果想要获取View的宽高,可以参考下篇博客

Android--获取View的宽高的几种方法

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值