About Bill Bejeck

Husband, father of 3, passionate about software development.

Android Drag and Drop Tutorial

This post is going to cover implementing Drag and Drop in an Android application.

(I am currently using version 4.0 of the sdk, but I originally wrote the code in this series with the 3.1 version.)

Why Use Drag and Drop

When I started working on my Android application, which involves moving a chess piece around a chess board, I chose to use drag and drop functionality for two reasons:

  1. I felt that drag and drop would get as close a possible to the experience of moving the piece around the board.
  2. By using drag and drop it will be much easier to determine valid moves by dropping the chess piece on an individual object (a square in the chess board in this case) rather than keeping track of the chess piece’s x,y coordinates. I’ll explain more on how I implemented this in the last installment of this series

My Drag and Drop Goals

I had 3 specific goals when it came to implementing drag and drop with regards to moving the chess piece on the board.

  1. When a user presses down and starts to drag, the chess piece would be replaced by a much lighter version of the original, making it obvious that it is being moved.
  2. I wanted to limit the area where the chess piece could be dragged, more specifically I don’t want players to drag the piece off the board
  3. If the player tries to drop the game piece that would result in an illegal move, I wanted the game piece to “snap back” to it’s original position.

Here i’m going to cover my first goal for drag and drop in my application.

Changing the ImageView on Drag Start

As I began working, I realized that the drag drop functionality did not support what I wanted right out of the box, but certainly with a little work there was enough in the api to give me what I was looking for. When the user presses down on the chess piece (which is an ImageView) to start a drag, here are the steps I take:

  1. Create a DragShadowBuilder object.
  2. Call the startDrag method.
  3. Hide the original ImageView (the chess piece) by calling setVisibility and passing in View.INVISIBLE, leaving only the DragShadowBuilder object visible, clearly indicating the drag has started.

The steps above are all done in the ImageView’s OnTouchListner object, in the implemented onTouch method. Here is the code:

@Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
            ClipData clipData = ClipData.newPlainText("", "");
            View.DragShadowBuilder dsb = new View.DragShadowBuilder(view);
            view.startDrag(clipData, dsb, view, 0);
            view.setVisibility(View.INVISIBLE);
            return true;
        } else {
            return false;
        }
    }

Changing the chess piece image on drag start achieved!

So far i covered how to hide an ImageView and just showed the DragShadowBuilder object at the start of a drag. Now i’m going to concentrate on restricting the drag area.

Trying to Restrict the Drag Area

Since my application involves moving a chess piece around board, I wanted to restrict the dragging area to the game board itself. My motivation is that the ImageView is hidden at the start of the drag. If the ImageView is dropped off the board, it will never reappear. That would leave my application in an inconsistent state. So I spent some time looking through the Android api, and Googling how I might limit the drag area. I came up with nothing. Then I took a step back and thought what problem am I trying to solve? Is it the user dragging the ImageView off the board? No, the real problem is the drop action is never handled, so I never get a chance to make the ImageView visible again. So I redefined my problem to be determining when a drop is valid or not.

Determining Valid Drops

To figure out how to determine valid drops, I went back to the Android Developer documentation. I honed in on handling drag end events. Here are the key points I found:

  • When a drag ends, an ACTION_DRAG_ENDED event is sent to all DragListeners.
  • A DragListener can determine more information about drag operations by calling the getResult method of the DragEvent.
  • If a DragListener returned true from an ACTION_DROP event, the getResult call will return true, otherwise false.

Now it is very clear to me what I can do when/if the user drags and drops the chess piece in an unintended area. My DragListener class already returns true for any event that is handled in the onDrag method. So a return value of false from getResult indicates the drop happened somewhere off the game board. What I need to do now is:

  1. When an ACTION_DRAG_ENDED event happens, call the getResult method
  2. If getResult returns false, immediately set the visibility of the ImageView (used at the start of the drag) back to visible.

Here is the code, the relevant lines are highlighted:

@Override
    public boolean onDrag(View view, DragEvent dragEvent) {
        int dragAction = dragEvent.getAction();
        View dragView = (View) dragEvent.getLocalState();
        if (dragAction == DragEvent.ACTION_DRAG_EXITED) {
            containsDragable = false;
        } else if (dragAction == DragEvent.ACTION_DRAG_ENTERED) {
            containsDragable = true;
        } else if (dragAction == DragEvent.ACTION_DRAG_ENDED) {
            if (dropEventNotHandled(dragEvent)) {
                dragView.setVisibility(View.VISIBLE);
            }
        } else if (dragAction == DragEvent.ACTION_DROP && containsDragable) {
            checkForValidMove((ChessBoardSquareLayoutView) view, dragView);
            dragView.setVisibility(View.VISIBLE);
        }
        return true;
    }

    private boolean dropEventNotHandled(DragEvent dragEvent) {
        return !dragEvent.getResult();
    }

Now users can drag and drop the ImageView anywhere and the game will not end up in an inconsistent state. My second goal is achieved.

The final installment covers moving a game piece as a result of a valid move or having that game piece “snap back” to it’s original postion when an invalid move is made.

Application Background Information

Some background information on my application might be helpful for this post. The game involves moving a single chess piece (a knight) around a chessboard. The chessboard is a TableLayout and each square is a subclass of LinearLayout and has an OnDragListener set. Additionally, each OnDragListener has a reference to a “mediator” object that:

  1. Handles communication between objects.
  2. Keeps track of the current square (landing square of the last valid move).

Determining Valid Moves

When the user starts to drag the ImageView and passes over a given square, the following actions are possible:

  • Use the ACTION_DRAG_ENTERED event to set the instance variable ‘containsDraggable’ to true.
  • Use the ACTION_DRAG_EXITED event to set ‘containsDraggable’ to false.
  • When an ACTION_DROP event occurs on a square, the mediator is asked if the attempted move is valid by checking all possible valid moves (pre-calculated) from the “current” square.

Here is the code with the relevant sections highlighted:

@Override
    public boolean onDrag(View view, DragEvent dragEvent) {
        int dragAction = dragEvent.getAction();
        View dragView = (View) dragEvent.getLocalState();
        if (dragAction == DragEvent.ACTION_DRAG_EXITED) {
            containsDragable = false;
        } else if (dragAction == DragEvent.ACTION_DRAG_ENTERED) {
            containsDragable = true;
        } else if (dragAction == DragEvent.ACTION_DRAG_ENDED) {
            if (dropEventNotHandled(dragEvent)) {
                dragView.setVisibility(View.VISIBLE);
            }
        } else if (dragAction == DragEvent.ACTION_DROP && containsDragable) {
            checkForValidMove((ChessBoardSquareLayoutView) view, dragView);
            dragView.setVisibility(View.VISIBLE);
        }
        return true;
    }

As you can see from above, regardless if the move is valid or not, the ImageView is made visible. By making the ImageView visible immediately after the drop, my goals of a seamless move, or “snapping back” to it’s original postion are met.

Moving the ImageView

Earlier, I mentioned that each square was a subclass of LayoutView. This was done for the ease of moving the ImageView from square to square. Here are the details from the checkForValidMove method (line 14 in the code sample above) that show how the move of the ImageView is accomplished.

private void checkForValidMove(ChessBoardSquareLayoutView view, View dragView) {
        if (mediator.isValidMove(view)) {
            ViewGroup owner = (ViewGroup) dragView.getParent();
            owner.removeView(dragView);
            view.addView(dragView);
            view.setGravity(Gravity.CENTER);
            view.showAsLanded();
            mediator.handleMove(view);
        }
    }

I hope that the reader will find this article helpful in their own Android development efforts.

Reference: Android Drag and Drop (Part 1)Android Drag and Drop (Part 2)Android Drag and Drop (Part 3) from our JCG partner Bill Bejeckat the Random Thoughts On Coding blog.

Related Articles :

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

4 Responses to "Android Drag and Drop Tutorial"

  1. Great tutorial.
    I wanted to switch the columns of a table with drag and drop. Thanks to your tutorial I found a way to do this …

  2. Anand S Pillai says:

    hi… thanx for this tutorial… I have a doubt on that mediator object. can you please add a snippet to create mediator obj.??

  3. Gangadhar says:

    I want to reset dragged view potion to its original position after successful drop. Please help me

Leave a Reply


× six = 24



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close