Late reply, but I also had this problem and fixed it with the following code. The solution for Action drop is answered here, so I don´t post it again. But if You want to detect it WHILE DRAGGING , you have to do that stuff inside DragEvent.ACTION_DRAG_LOCATION
.
get x y of current drag event:
int x_cord = (int) event.getX();
int y_cord = (int) event.getY();
now calculate the size of the rect. For that (in my case) if have to divide the size of the view because the drag position was in the center of it and then calculate the top/left/right/bottom:
int left = (int) (x_cord - halfViewSize);
int top = (int) (y_cord - halfViewSize);
int right = (int) (x_cord + halfVaieSize);
int bottom = (int) (y_cord + halfViewSize);
I casted the value because in my case halfViewSize was a float
. If you have an integer
, you don´t need to cast.
Now you can build a rect with these values:
Rect rect = new Rect(left, top, right, bottom);
create a method which checks if the rect intersects with a rect of your childViews:
private boolean collideWithOthers(Rect rect) {
int count = yourParentLayout.getChildCount();
boolean intersects = false;
for (int i = 0; i < count; i++) {
ImageView squareInside = (ImageView) yourParentLayout.getChildAt(i);
Rect rectInside = squareInside.getCollisionRect();
if (rectInside.intersect(rect)) {
Log.d("TAG", "ATTENTION INTERSECT!!!");
intersects = true;
break;//stop the loop because an intersection is detected
}
}
return intersects;
}
Now you can do this stuff inside ACTION_DRAG_LOCATION
:
int x_cord = (int) event.getX();
int y_cord = (int) event.getY();
int left = (int) (x_cord - halfViewSize);
int top = (int) (y_cord - halfViewSize);
int right = (int) (x_cord + halfVaieSize);
int bottom = (int) (y_cord + halfViewSize);
Rect rect = new Rect(left, top, right, bottom);
boolean collide = collideWithOthers(rect);
I hope this will fit to your needs, if not, maybe it´s helpful for others.