android之View坐标系看下图就明白了:

引自官方文档:

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播放音乐文件代码
  2. Android闪光灯开关
  3. Android下修改SeekBar样式
  4. 编写android拨打电话apk应用实例代码
  5. Android中和service进行本地通讯
  6. 分享一段Android基于https协议POST数据的代码
  7. android 软键盘回车变搜索
  8. Android文件拷贝
  9. 处理空列表

随机推荐

  1. Android之来历
  2. Android下EditText中的字体不统一问题
  3. Android(安卓)动态菜单实现实例代码
  4. Android+Jquery Mobile学习系列(1)-开发
  5. Android应用开发资源
  6. App 开发 Android Fragments 的详细使用
  7. Android(安卓)OpenGL ES(九):绘制线段Line
  8. Android最佳实践之:代码性能优化——Stric
  9. [置顶] Android应用程序签名
  10. Android将后台应用唤起到前台,唤醒APP;