获取 View
坐标在 Android
开发中非常常见。今天carson
将详细给大家讲解 获取 View
坐标常用6种方式:
获得 View
相对 父View
的坐标
view.getLeft();
view.getTop();
view.getRight();
view.getBottom();
View的位置由4个顶点决定的(如下A、B、C、D)
4个顶点的位置描述分别由4个值决定:(请记住:View的位置是相对于父控件而言的)
获得点击事件处 相对点击控件 & 屏幕的坐标
该方式是通过motionEvent获取的
motionEvent event;
event.getX();
event.getY();
event.getRawX();
event.getRawY();
获取控件 相对 窗口Window 的位置
int[] location = new int[2];
view.getLocationInWindow(location);
int x = location[0]; // view距离window 左边的距离(即x轴方向)
int y = location[1]; // view距离window 顶边的距离(即y轴方向)
// 注:要在onWindowFocusChanged()里获取,即等window窗口发生变化后
获得 View 相对 屏幕 的绝对坐标
int[] location = new int[2];
view.getLocationOnScreen(location);
int x = location[0]; // view距离 屏幕左边的距离(即x轴方向)
int y = location[1]; // view距离 屏幕顶边的距离(即y轴方向)
// 注:要在view.post(Runable)里获取,即等布局变化后
View可见部分 相对于 屏幕的坐标。
Rect globalRect = new Rect();
view.getGlobalVisibleRect(globalRect);
globalRect.getLeft();
globalRect.getRight();
globalRect.getTop();
globalRect.getBottom();
View可见部分 相对于 自身View位置左上角的坐标。
Rect localRect = new Rect();
view.getLocalVisibleRect(localRect);
localRect.getLeft();
localRect.getRight();
localRect.getTop();
localRect.getBottom();
本文对Android获取View坐标位置的方式进行了全面讲解,总结如下:
Android
开发中的相关知识,感兴趣的同学可以继续关注本人博客Carson_Ho的开发笔记