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



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.)


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