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:

01@Override
02    public boolean onTouch(View view, MotionEvent motionEvent) {
03        if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
04            ClipData clipData = ClipData.newPlainText("", "");
05            View.DragShadowBuilder dsb = new View.DragShadowBuilder(view);
06            view.startDrag(clipData, dsb, view, 0);
07            view.setVisibility(View.INVISIBLE);
08            return true;
09        } else {
10            return false;
11        }
12    }

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:

01@Override
02    public boolean onDrag(View view, DragEvent dragEvent) {
03        int dragAction = dragEvent.getAction();
04        View dragView = (View) dragEvent.getLocalState();
05        if (dragAction == DragEvent.ACTION_DRAG_EXITED) {
06            containsDragable = false;
07        } else if (dragAction == DragEvent.ACTION_DRAG_ENTERED) {
08            containsDragable = true;
09        } else if (dragAction == DragEvent.ACTION_DRAG_ENDED) {
10            if (dropEventNotHandled(dragEvent)) {
11                dragView.setVisibility(View.VISIBLE);
12            }
13        } else if (dragAction == DragEvent.ACTION_DROP && containsDragable) {
14            checkForValidMove((ChessBoardSquareLayoutView) view, dragView);
15            dragView.setVisibility(View.VISIBLE);
16        }
17        return true;
18    }
19 
20    private boolean dropEventNotHandled(DragEvent dragEvent) {
21        return !dragEvent.getResult();
22    }

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:

01@Override
02    public boolean onDrag(View view, DragEvent dragEvent) {
03        int dragAction = dragEvent.getAction();
04        View dragView = (View) dragEvent.getLocalState();
05        if (dragAction == DragEvent.ACTION_DRAG_EXITED) {
06            containsDragable = false;
07        } else if (dragAction == DragEvent.ACTION_DRAG_ENTERED) {
08            containsDragable = true;
09        } else if (dragAction == DragEvent.ACTION_DRAG_ENDED) {
10            if (dropEventNotHandled(dragEvent)) {
11                dragView.setVisibility(View.VISIBLE);
12            }
13        } else if (dragAction == DragEvent.ACTION_DROP && containsDragable) {
14            checkForValidMove((ChessBoardSquareLayoutView) view, dragView);
15            dragView.setVisibility(View.VISIBLE);
16        }
17        return true;
18    }

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.

01private void checkForValidMove(ChessBoardSquareLayoutView view, View dragView) {
02        if (mediator.isValidMove(view)) {
03            ViewGroup owner = (ViewGroup) dragView.getParent();
04            owner.removeView(dragView);
05            view.addView(dragView);
06            view.setGravity(Gravity.CENTER);
07            view.showAsLanded();
08            mediator.handleMove(view);
09        }
10    }

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 :

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值