Android:获取View视图在屏幕坐标方法总结

您所在的位置:网站首页 获取控件在屏幕的位置 Android:获取View视图在屏幕坐标方法总结

Android:获取View视图在屏幕坐标方法总结

2023-12-19 20:15| 来源: 网络整理| 查看: 265

一 View在屏幕上的占用区域、显示区域、绘制区域

在这里插入图片描述 在这里插入图片描述

二 padding值喝Margin值的获取

根据上图可以知道,padding其实就是代表view的内容与view之间的距离,而Margin值代表的则是view和父view之间的距离 padding和margin的值可以在xml文件中设置,所以只要xml文件被加载,不论View是否被绘制,都可以获取这些值。 在这里插入图片描述

三 View的getLeft()、getTop()、getRight()、getBottom()方法

在这里插入图片描述 如果你要得到子view的宽高,通过这四个值也可以得到:

childview_width=getRight()-getLeft(); childview_height=getBottom()-getTop();

但是与上面的magin和padding值不同,这四个值需要在完成测量的时候才能获取到值,在测量前调用方法会返回0, 例如:可以在View的post(Runnable)中调用,或者在View的onClick点击事件中调用,或者在Activity(或Fragment)的onPause()方法中调用。在Activity(或Fragment)的onResume()中调用不行,因为View是在onResume()方法执行时进行绘制的,此时调用View可能还没有绘制完,所以返回的是0.

四 MotionEvent里获取坐标的方法

MotionEvent的getX(),getY(),getX(int),getY(int),getRawX(),getRawY(),getRawX(int),getRawY(int)方法: 在这里插入图片描述

五 getLocationInWindow()和getLocationOnScreen()

在这里插入图片描述

getLocationInWindow是以B为原点的C的坐标 getLocationOnScreen以A为原点。

5.1 getLocationInWindow()

: getLocationInWindow():一个控件在其父窗口中的坐标位置 使用方法:View.getLocationInWindow(int[] location)

start = (Button) findViewById(R.id.start); int []location=new int[2]; start.getLocationOnScreen(location); int x=location[0];//获取当前位置的横坐标 int y=location[1];//获取当前位置的纵坐标

在这里插入图片描述

5.2 getLocationOnScreen():

一个控件在其整个屏幕上的坐标位置 使用方法:View.getLocationOnScreen(int[] location)

start = (Button) findViewById(R.id.start); int []location=new int[2]; start.getLocationOnScreen(location); int x=location[0];//获取当前位置的横坐标 int y=location[1];//获取当前位置的纵坐标

在这里插入图片描述

六 getGlobalVisibleRect():全局可见区域

View可见部分相对于屏幕的坐标。 代码示例:

Rect globalRect = new Rect(); view.getGlobalVisibleRect(globalRect); globalRect.getLeft(); globalRect.getRight(); globalRect.getTop(); globalRect.getBottom();

示意图: 在这里插入图片描述

七 getLocalVisibleRect():局部可见区域

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

示例代码:

Rect localRect = new Rect(); view.getLocalVisibleRect(localRect); localRect.getLeft(); localRect.getRight(); localRect.getTop(); localRect.getBottom(); 示意图: ![在这里插入图片描述](https://img-blog.csdnimg.cn/6c91e110dd2a416cbe820b59531e3b3f.png) 八 总结

在这里插入图片描述 参考实例:https://zhuanlan.zhihu.com/p/274321442



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3