Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Implementing Drag and Drop

Author: Ian Darwin -- Published? true -- FormatLanguage: W

Problem:

You want to implement drag-and-drop, similar to what the Home Screen / Launcher does when you long-press on an application icon.

Solution:

Use the drag-and-drop API, supported since Android 3.0 and even in the compat libraries.

Discussion:

The normal use of drag=and-drop is to request a change, such as removing an application, removing an item from a list, and so on. To move information from the source View (e.g., the list item from where you start the drag) to the drop target, there is a special wrapper object called a ClipData. The ClipData can either hold an Android URI (e.g., for the datatype and object identity) for the object to be dropped, or, some arbitrary data. The URI will usually be passed to a ContentProvider for processing.

The basic steps in a drag-and-drop are:

1) Implement an OnDragListener; in its onDrag() method you should be prepared for the various Action events such as ACTION_DRAG_STARTED, ACTION_DRAG_ENTERED, ACTION_DRAG_EXITED, ACTION_DROP, and ACTION_DRAG_ENDED.

2) Register this listener using view.setOnDragListener()

3) Usually in an onItemLongClick() or similar method, start the drag, using

ClipData cd = ClipData.newUri(contentResolver, "Drag Label", contentUri); v.startDrag(cd, dropShadowBuildfer, null, 0);

4) For ACTION_DRAG_ENTERED on a drop target, highlight the view to direct the user's attention to it as a target, as by changing the background color, the image, or similar.

5) For ACTION_DROP, in the drop target, perform the action, for example:

contentResolver.delete(event.getClipData().getItemAt(0));

6) For ACTION_DRAG_EXITED and/or ACTION_DRAG_ENDED, do any cleanups required (e.g., undo changes made in the ACTION_DRAG_ENTERED case).

No records found.