获取 View 坐标在 Android 开发中非常常见。今天将详细给大家讲解 获取 View 坐标常用6种方式:
1. 应用场景
获得 View 相对 父View 的坐标
2. 使用
view.getLeft();view.getTop();view.getRight();view.getBottom();
3. 具体描述
View的位置由4个顶点决定的(如下A、B、C、D)
View的顶点
4个顶点的位置描述分别由4个值决定:(请记住:View的位置是相对于父控件而言的)
1. 应用场景
获得点击事件处 相对点击控件 & 屏幕的坐标
2. 使用
该方式是通过motionEvent获取的
motionEvent event;event.getX();
event.getY();event.getRawX();
event.getRawY();
3. 具体介绍
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. 示意图
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. 示意图
1. 应用场景
View可见部分 相对于 屏幕的坐标。
2. 具体使用
Rect globalRect = new Rect();
view.getGlobalVisibleRect(globalRect);
globalRect.getLeft();
globalRect.getRight();
globalRect.getTop();
globalRect.getBottom();
3. 示意图
1. 应用场景
View可见部分 相对于 自身View位置左上角的坐标。
2. 具体使用
Rect localRect = new Rect();
view.getLocalVisibleRect(localRect);
localRect.getLeft();
localRect.getRight();
localRect.getTop();
localRect.getBottom();
3. 示意图
本文对Android获取View坐标位置的方式进行了全面讲解,总结如下:
#更多Android学习内容关注我的博客
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:http://blog.itpub.net/69952849/viewspace-2663883/