Android get bounding rectangle of a View

后端 未结 5 605
渐次进展
渐次进展 2020-12-08 02:17

I\'m implementing a drag and drop for an Android application. In order to know if the drop happens inside the drop target, I need to know the bounding rectangle of the drop

5条回答
  •  一整个雨季
    2020-12-08 02:37

    This code takes into consideration, the perimeter of the Views involved and only returns true when the dragged View is fully inside the drop zone.

    public boolean containsView(View dropZone, View draggedView){
         // Create the Rect for the view where items will be dropped
         int[] pointA = new int[2];
         dropZone.getLocationOnScreen(pointA);
         Rect rectA = new Rect(pointA[0], pointA[1], pointA[0] + dropZone.getWidth(), pointA[1] + dropZone.getHeight());
    
         // Create the Rect for the view been dragged
         int[] pointB = new int[2];
         draggedView.getLocationOnScreen(pointB);
         Rect rectB = new Rect(pointB[0], pointB[1], pointB[0] + draggedView.getWidth(), pointB[1] + draggedView.getHeight());
    
         // Check if the dropzone currently contains the dragged view
         return rectA.contains(rectB);
    }
    

提交回复
热议问题