Tuesday, November 1, 2011

Drag and Drop (Honeycomb/ICS)

Drag and drop is already available with Honeycomb and up. In this example, we will see how to implement a simple Drag and Drop Operation.

We have a ListView with some items. The other half of the screen would have a drop area which has a single TextView. We will see, how to drag items from the ListView, drop them into the drop area, which will update the TextView with the list item's title, and also, that particular item would be removed from the ListView.

We will trigger the drag operation, when you long tap on an item in the ListView. After the drag operation is started, you will see a floating view of the selected item, which you can move around the screen. When you approach the drop area, the background of the drop area would change, which means that you can now drop your item. Once you leave the item, the TextView inside the drop area will show the text of the selected item.





This should also work on Ice Cream Sandwich. You can find the whole source code here. The code is quite self-explanatory. But, if you have any queries, let me know through the comment form. There are a few comments in the code to help you.

11 comments:

  1. Hey,
    Nice blog. Check out mine at

    Haircules Speaketh!

    Love is two way!

    And do vote em if you find them interesting.

    ReplyDelete
  2. Please help! I tried to view your apps. But there are many errors in both java classes :(

    ReplyDelete
  3. Hi I managed to get it working thanks for the code. I'm wondering if it is possible to drag the items in the listview into the drop area and then allow the items to be dragged around inside the drop area? Thanks! Would hope to hear a reply from you!

    ReplyDelete
  4. @JSbuTa: Well, Haven't tried that. But then you will have to use a Absolute layout where you can precisely drop off the item. I am not sure yet.

    ReplyDelete
  5. hmm
    all comments are nice and informative with their links
    i want more information about ANDROID.

    ReplyDelete
  6. hey man, is it possible to do the other way round.. Because i want to drag a button and drop it onto the list.

    ReplyDelete
  7. I modified the drag and drop listview and updated it to drag and drop expandable listview, see the code and explanations here

    ReplyDelete
  8. Hi. I'm actually doing a project to regard of drag and drop. I came across your post and found it really useful. However, I encounter quite a few errors:

    import android.content.ClipData;
    import android.content.ClipData.Item;
    import android.content.ClipDescription;
    import android.view.DragEvent;
    import android.view.View.OnDragListener;

    Please help as i'm a new learner to Java :(

    ReplyDelete
  9. hi i want to make the animation base game so i want drop the target any time so please say me how to drop the target in runtime please help me yar
    thanks in advance

    ReplyDelete