Android 中如何正确获取 View 坐标位置(看了就懂)

在我们 Android 开发过程中经常使用到获取 View 坐标的方式做相关的逻辑判断,主要是用到一下几种方法:

  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)

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 坐标位置的方式进行了全面讲解,总结如下:

参考 https://blog.csdn.net/carson_ho/article/details/103342511

posted @   mahy  阅读(4566)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 2 本地部署DeepSeek模型构建本地知识库+联网搜索详细步骤
点击右上角即可分享
微信分享提示