Filip V
Filip V

Reputation: 435

Android drag and drop on another view

I'm making Android application and I want this feature: User can drag some view and when he dropt on some another view, I can register that he dropt on some view and do some work with that view.

For example:

There are two ImageView, one blue one red, and there is thrid ImageView, when user dropt third ImageView on blue one I have to call method1() and otherwise when user dropt on red one I have to call method2().

I have implemented standrad drag listener:

imageView.setOnDragListener(new View.OnDragListener() {
        @Override
        public boolean onDrag(View v, DragEvent event) {
            switch(event.getAction())
            {
                case DragEvent.ACTION_DRAG_STARTED:
                    Log.e(msg, "Action is DragEvent.ACTION_DRAG_STARTED");

                    return true;

                case DragEvent.ACTION_DRAG_ENTERED:
                    Log.e(msg, "Action is DragEvent.ACTION_DRAG_ENTERED");
                    return true;

                case DragEvent.ACTION_DRAG_EXITED :
                    Log.e(msg, "Action is DragEvent.ACTION_DRAG_EXITED");
                    break;

                case DragEvent.ACTION_DRAG_LOCATION  :
                    Log.e(msg, "Action is DragEvent.ACTION_DRAG_LOCATION");

                    break;

                case DragEvent.ACTION_DRAG_ENDED   :
                    Log.e(msg, "Action is DragEvent.ACTION_DRAG_ENDED");

                    break;

                case DragEvent.ACTION_DROP:
                    Log.e(msg, "ACTION_DROP event");

                    break;
                default: break;
            }
            return true;
        }
    });

Upvotes: 0

Views: 142

Answers (2)

Hemant Sharma
Hemant Sharma

Reputation: 1

So, you need to call view.startDrag in order to listen to the callbacks.

You can move your view in ACTION_MOVE, and check the intersection in ACTION_DROP.

This can also be directly achieved by OnTouchListener.

You can get the full example here.

Upvotes: 0

Greg Ennis
Greg Ennis

Reputation: 15379

You don't need to calculate rects. You should call setOnDragListener two times, once on the red image view to handle the drop events on it, and once on the blue image view to handle drop events on it. Also just in case, I don't see the code where you need to call startDrag on the view that user is dragging during the touch event to start the drag.

Upvotes: 1

Related Questions