erik erik - 3 months ago 16
Android Question

How do I get the release X and Y position of a Drag?

I have a

DragListener
of which I would like to get the coordinates of where the view is released. But no matter where I drop it I get
x = 0
and
y = 0
. Obviously I am doing something wrong. How do I get the
x
and
y
of the release point?

this.setOnDragListener(new View.OnDragListener() {
CustomIcon temp;
CustomIcon dragging;
Boolean thisOne;

public boolean onDrag(View v, DragEvent event) {

for(int i= 0; i<mIcons.size();i++) {
temp = mIcons.get(i);
thisOne = temp.getDragging();
if(thisOne) {
dragging = temp;
}
}
final int action = event.getAction();
switch (action) {
case DragEvent.ACTION_DRAG_STARTED: {

Toast.makeText(getContext(), "Dragging: "+v+" Width:"+dragging.getWidth()+ " X:"+dragging.getX(),Toast.LENGTH_SHORT).show();
dragging.setVisibility(View.INVISIBLE);

} break;

case DragEvent.ACTION_DRAG_ENDED: {

dragging.setVisibility(View.VISIBLE);
dragging.stopDragging();

// WHERE MY PROBLEM IS:
Toast.makeText(getContext(), "Result: "+event.getResult()+" endX:"+(int) event.getX() + " endY:"+event.getY(),Toast.LENGTH_SHORT).show();
final boolean dropped = event.getResult();

} break;
}
return false;
}
});

Answer Source

I think your case is listening to the wrong event. http://developer.android.com/reference/android/view/DragEvent.html#getX()

public float getX ()

Gets the X coordinate of the drag point. The value is only valid if the event action is ACTION_DRAG_LOCATION or ACTION_DROP.

Try changing your case to DragEvent.ACTION_DROP