Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 459
TheModularMind Avatar asked Jun 04 '14 21:06

TheModularMind


People also ask

When to use Relative layout?

A RelativeLayout is a very powerful utility for designing a user interface because it can eliminate nested view groups and keep your layout hierarchy flat, which improves performance. If you find yourself using several nested LinearLayout groups, you may be able to replace them with a single RelativeLayout .

How do you close a whole app on Android?

To close apps on Android, swipe up from the bottom of the screen and hold until the recent apps menu pops up (if you use gesture navigations). If you use button navigation, tap on the recent apps button.

How to include a layout in Android?

To efficiently reuse complete layouts, you can use the <include/> and <merge/> tags to embed another layout inside the current layout. Reusing layouts is particularly powerful as it allows you to create reusable complex layouts. For example, a yes/no button panel, or custom progress bar with description text.


1 Answers

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.

like image 131
matiash Avatar answered Nov 14 '22 23:11

matiash