Search code examples
androidintersectionandroid-framelayoutrect

Android intersection of views not working


I have two very simple views set up in Android:

screenshot

and here is my code to see if they overlap but for some reason the code always returns "IS NOT overlapping":

private FrameLayout firstView; private FrameLayout secondView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    firstView = (FrameLayout)findViewById(R.id.numberOne);
    secondView = (FrameLayout)findViewById(R.id.numberTwo);

    if (containsView(secondView, firstView)) {
        Toast.makeText(this, "IS overlapping", Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(this, "IS NOT overlapping", Toast.LENGTH_LONG).show();
    }
}


public boolean containsView(View firstView, View secondView){
    int[] pointA = new int[2];
    firstView.getLocationOnScreen(pointA);
    Rect rectA = new Rect(pointA[0], pointA[1], pointA[0] + firstView.getWidth(), pointA[1] + firstView.getHeight());

    int[] pointB = new int[2];
    secondView.getLocationOnScreen(pointB);
    Rect rectB = new Rect(pointB[0], pointB[1], pointB[0] + secondView.getWidth(), pointB[1] + secondView.getHeight());

    return Rect.intersects(rectA, rectB);
}

Solution

  • You are Checking the Views locations before they got measured and being drawn to the screen. the call firstView.getWidth is probably 0. you can check it by logging.

    add TreeObserver or something like: secondView.addOnLayoutChangeListener.

    by the way i didn't check if your intersect algorithm is correct, only notified you about your error.