android view相对于根布局的坐标获取

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;    }