使用getLocationInWindow或getLocationOnScreen获得View在屏幕中的坐标
2016-07-12 10:15
1241 查看
在View提供了两个方法这样的方法,我们可以利用它们来获得View在屏幕中的坐标:
另一个是 :
关于这两个方法的调用,在oncreate或onstart是获取不到值的,在onresume可能会获取到值,当然在点击事件的时候是可以获取到值,
我的做法如果有需要就是利用handler延时0.1秒来获取此值,伪代码如下:
/** * <p>Computes the coordinates of this view in its window. The argument * must be an array of two integers. After the method returns, the array * contains the x and y location in that order.</p> * * @param location an array of two integers in which to hold the coordinates */ public void getLocationInWindow(@Size(2) int[] location)
用法如下:
int[] location = new int[2]; view.getLocationInWindow(location);//获取控件在window里的位置,0位表示x轴方向的坐标,说白点就是view距左边的距离,1位表示y轴的方向,是view距离顶部(包括状态栏)的位置
另一个是 :
public void getLocationOnScreen(@Size(2) int[] location) 或他的一个重载方法
public int[] getLocationOnScreen()关于screen我们比较好理解,就可以以为是手机屏幕,而窗体window我举例说下:比如说此视图在一个对话框里那么getLocationInWindow就是相对这个对话框的位置而言的.
关于这两个方法的调用,在oncreate或onstart是获取不到值的,在onresume可能会获取到值,当然在点击事件的时候是可以获取到值,
我的做法如果有需要就是利用handler延时0.1秒来获取此值,伪代码如下:
new Handler().postDelayed(new Runnable() { @Override public void run() { int[] location=new int[2]; view.getLocationOnScreen(location); } }, 100); 最后我再把获取状态栏的方法贴出来吧,也许有人用到了
/** * 获得状态栏的高度 */ public int getStatusBarHeight(Context context) { int result = 0; int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { result = context.getResources().getDimensionPixelSize(resourceId); } return result; }有不对之处,欢迎指正
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Android IPC进程间通讯机制
- Android Manifest 用法
- [转载]Activity中ConfigChanges属性的用法
- Android之获取手机上的图片和视频缩略图thumbnails
- Android之使用Http协议实现文件上传功能
- Android学习笔记(二九):嵌入浏览器
- android string.xml文件中的整型和string型代替
- i-jetty环境搭配与编译
- android之定时器AlarmManager
- android wifi 无线调试
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- android 代码实现控件之间的间距
- android FragmentPagerAdapter的“标准”配置
- Android"解决"onTouch和onClick的冲突问题
- android:installLocation简析
- android searchView的关闭事件
- SourceProvider.getJniDirectories