Android - How to know if a view overlay another vi

2019-02-13 17:46发布

I have a RelativeLayout with two views inside. The view1 is recreated inside the layout in a random position every ten seconds. view2 is in a static position and is bigger then view1. I want to know when the first view is created inside the second view area, how can I do that?

I'm currently trying this code but id doesn't work well.

        if (paramsView1.topMargin > View2Ystart
            && paramsView1.topMargin < View2Yend
            && paramsView1.leftMargin > View2Xstart
            && paramsView1.leftMargin < View2Xend) {
        return true
    }
    else
        return false;

It returns true only if view1 is touching a side of view2. I want it returns true only if view1 is totally inside view2.

1条回答
狗以群分
2楼-- · 2019-02-13 18:06

You should use getLeft(), getRight(), getTop() and getBottom().

if (v1.getTop() >= v2.getTop() &&
    v1.getLeft() >= v2.getLeft() &&
    v1.getRight() <= v2.getRight() &&
    v1.getBottom() <= v2.getBottom()) { ...

Be mindful that these values will be available when the parent is laid out, i.e. not immediately after addView().

Another possible solution, which may be more flexible, is to build Rect instances with each view's coordinates, e.g.

Rect rect1 = new Rect(v1.getLeft(), v1.getTop(), v1.getRight(), v1.getBottom());
Rect rect2 = new Rect(v2.getLeft(), v2.getTop(), v2.getRight(), v2.getBottom());

Then you can use rect1.contains(rect2) or Rect.intersects(rect1, rect2) or any other combination.

查看更多
登录 后发表回答