简体   繁体   中英

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;
    }
});

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

i had a problem like this. there is 3 important thing 1- set drag listener on parent view(for ex: linear layout or relative or .. ) 2- use ACTION_DROP for taking cooridinate x,y and not ACTION_DRAG_ENDED 3- set startDrag() on view that you want to drag it over parent. for example you can use setonlongclick() and set starDrag() inside longclick event

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM