简体   繁体   中英

Android - How to know if a view overlay another view in RelativeLayout

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.

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, ie not immediately after addView() .

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM