使用getLocationInWindow或getLocationOnScreen获得View在屏幕中的坐标

来源:互联网 发布:打印机扫描软件通用 编辑:程序博客网 时间:2024/05/28 23:10

在View提供了两个方法这样的方法,我们可以利用它们来获得View在屏幕中的坐标:

/** * <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;}
有不对之处,欢迎指正微笑

0 0
原创粉丝点击