Android Core

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 :

Bill Bejeck

Husband, father of 3, passionate about software development.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

7 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Christian Skubich
12 years ago

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 …

Abbas
Abbas
11 years ago

Hi, this is exactly my objective as well, I was wondering if you could give me any tips? Thanks

altaf2892
8 years ago

i want source code ……please give me at my email address .. altafshikah2892@gmail.com

Anand S Pillai
Anand S Pillai
11 years ago

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

Gangadhar
Gangadhar
10 years ago

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

Anne
Anne
9 years ago

I just wanted to ask if what are the libraries that were use by using this drag and drop option.

Suvab
Suvab
5 years ago

What is (ChessBoardSquareLayoutView) this class? Is it user-defined.? can you please send me the code for this? and Also the mediator object. All and all thank you, your blog was very much helpful.

Back to top button