Android日常学习:如何高效 & 正确地获取View的坐标位置?
获取 View 坐标在 Android 开发中非常常见。今天将详细给大家讲解 获取 View 坐标常用6种方式:
getLeft()、getTop()、getRight()、getBottom()getX()、getY()、getRawX()、getRawY()getLocationOnScreen()getLocationInWindow()getGlobalVisibleRect()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)
image
View的顶点
4个顶点的位置描述分别由4个值决定:(请记住:View的位置是相对于父控件而言的)
image方式2:getX()、getY()、getRawX()、getRawY()
1. 应用场景
获得点击事件处 相对点击控件 & 屏幕的坐标
2. 使用
该方式是通过motionEvent获取的
motionEventevent;event.getX();event.getY();event.getRawX();event.getRawY();
3. 具体介绍
image方式3:getLocationInWindow()
1. 应用场景
获取控件 相对 窗口Window 的位置
2. 具体使用
int[]location=newint[2];view.getLocationInWindow(location);intx=location[0];//view距离window左边的距离(即x轴方向)inty=location[1];//view距离window顶边的距离(即y轴方向)//注:要在onWindowFocusChanged()里获取,即等window窗口发生变化后
3. 示意图
image方式4:getLocationOnScreen()
1. 应用场景
获得 View 相对 屏幕 的绝对坐标
2. 使用
int[]location=newint[2];view.getLocationOnScreen(location);intx=location[0];//view距离屏幕左边的距离(即x轴方向)inty=location[1];//view距离屏幕顶边的距离(即y轴方向)//注:要在view.post(Runable)里获取,即等布局变化后
3. 示意图
image方式5:getGlobalVisibleRect()
1. 应用场景
View可见部分 相对于 屏幕的坐标。
2. 具体使用
RectglobalRect=newRect();view.getGlobalVisibleRect(globalRect);globalRect.getLeft();globalRect.getRight();globalRect.getTop();globalRect.getBottom();
3. 示意图
image方式6:getLocalVisibleRect()
1. 应用场景
View可见部分 相对于 自身View位置左上角的坐标。
2. 具体使用
RectlocalRect=newRect();view.getLocalVisibleRect(localRect);localRect.getLeft();localRect.getRight();localRect.getTop();localRect.getBottom();
3. 示意图
image总结
本文对Android获取View坐标位置的方式进行了全面讲解,总结如下:
#更多Android学习内容关注我的博客
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。