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;
    }
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值