android之View坐标系看下图就明白了:
android view相对于根布局的坐标获取_第1张图片

引自官方文档:

Position
The geometry of a view is that of a rectangle. A view has a location, expressed as a pair of left and top coordinates, and two dimensions, expressed as a width and a height. The unit for location and dimensions is the pixel.

It is possible to retrieve the location of a view by invoking the methods getLeft() and getTop(). The former returns the left, or X, coordinate of the rectangle representing the view. The latter returns the top, or Y, coordinate of the rectangle representing the view. These methods both return the location of the view relative to its parent. For instance, when getLeft() returns 20, that means the view is located 20 pixels to the right of the left edge of its direct parent.

In addition, several convenience methods are offered to avoid unnecessary computations, namely getRight() and getBottom(). These methods return the coordinates of the right and bottom edges of the rectangle representing the view. For instance, calling getRight() is similar to the following computation: getLeft() + getWidth() (see Size for more information about the width.)

放送一段代码,在复杂的UI嵌套中,想要获得当前View相对于activity根布局的x,y坐标的代码段:

    private float getX(View v) {        if (v != null) {            return v.getLeft() + getParentX(v.getParent());        }        return 0;    }    private float getParentX(ViewParent parent) {        if (parent != null && parent instanceof ViewGroup) {            return ((ViewGroup) parent).getLeft() + getParentX(parent.getParent());        }        return 0;    }    private float getY(View v) {        if (v != null) {            return v.getTop() + getParentY(v.getParent()) - getSystemBarHeight();        }        return 0;    }    private float getParentY(ViewParent parent) {        if (parent != null && parent instanceof ViewGroup) {            return ((ViewGroup) parent).getTop() + getParentY(parent.getParent());        }        return 0;    }    private float getSystemBarHeight() {        Rect rectangle = new Rect();        mActivity.getWindow().getDecorView().getWindowVisibleDisplayFrame(rectangle);        return rectangle.top;    }

更多相关文章

  1. Android 如何在Java代码中手动设置控件的marginleft
  2. Android 布局 优先显示右侧的控件
  3. Android 自动换行流式布局的RadioGroup
  4. android播放音乐文件代码
  5. LinearLayout(线性布局)
  6. 分享一段Android基于https协议POST数据的代码
  7. 编写android拨打电话apk应用实例代码
  8. android 用代码编写linearlayout布局
  9. android延迟进入主界面和点击按钮进入主界面代码

随机推荐

  1. Android(安卓)JNI详述
  2. Android中的多线程
  3. 【OpenCV4Android学习一】 Android(安卓)
  4. Android 更改软键盘Enter键为搜索
  5. Android集成Huawei PUSH(四)——客户端开发
  6. android 分辨率问题
  7. Android通过JNI调用驱动程序(完全解析实
  8. Android应用程序添加自定义的property属
  9. Android(1.初识Android应用程序目录)
  10. android 出现gen already exists but is