detect if views are overlapping

Berserk thanks you for help! After some experiments I wrote method which detect view is overlapped or not for my case!

private boolean isViewOverlapping(View firstView, View secondView) {
        int[] firstPosition = new int[2];
        int[] secondPosition = new int[2];

        firstView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        firstView.getLocationOnScreen(firstPosition);
        secondView.getLocationOnScreen(secondPosition);

        int r = firstView.getMeasuredWidth() + firstPosition[0];
        int l = secondPosition[0];
        return r >= l && (r != 0 && l != 0);
    }

You can also use Rect.intersect() to find overlapping views.

    int[] firstPosition = new int[2];
    int[] secondPosition = new int[2];

    firstView.getLocationOnScreen(firstPosition);
    secondView.getLocationOnScreen(secondPosition);

    // Rect constructor parameters: left, top, right, bottom
    Rect rectFirstView = new Rect(firstPosition[0], firstPosition[1],
            firstPosition[0] + firstView.getMeasuredWidth(), firstPosition[1] + firstView.getMeasuredHeight());
    Rect rectSecondView = new Rect(secondPosition[0], secondPosition[1],
            secondPosition[0] + secondView.getMeasuredWidth(), secondPosition[1] + secondView.getMeasuredHeight());
    return rectFirstView.intersect(rectSecondView);

This is similar to the answer from Marcel Derks, but was written without the need for an additional import. It uses the basic code that forms Rect.intersect without creating the Rect objects.

private boolean isViewOverlapping(View firstView, View secondView) {
    int[] firstPosition = new int[2];
    int[] secondPosition = new int[2];

    firstView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
    firstView.getLocationOnScreen(firstPosition);
    secondView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
    secondView.getLocationOnScreen(secondPosition);

    return firstPosition[0] < secondPosition[0] + secondView.getMeasuredWidth()
            && firstPosition[0] + firstView.getMeasuredWidth() > secondPosition[0]
            && firstPosition[1] < secondPosition[1] + secondView.getMeasuredHeight()
            && firstPosition[1] + firstView.getMeasuredHeight() > secondPosition[1];
}

You are not required to force a view measurement, but it is done for good measure ;)

Tags:

Android

View