How to stop an ImageView being dragged before the user stops dragging

| | August 5, 2015

I am making a maze game using Android Studio. I have a GridLayout on the bottom layer of the layout, each cell contains a custom LinearLayout. Some of these LinearLayouts have a special boolean property isWall. If isWall = true I put a different image in the LinearLayout.

The “start” cell of the grid contains a child ImageView of a ball. I want the user to be able to drag the ball through the maze and drop it on any non-wall LinearLayout. I don’t want the ImageView to be dragged across any cell containing a LinearLayout where isWall = true. I know how to get the DragListener to return false after the user drags the ImageView across a “wall” and drops it on the other side, and I basically have the ball return to the cell it was in before that drag.

How to I make the ImageView itself stop mid-drag, thus forcing the user to stay inside the maze walls?

One Response to “How to stop an ImageView being dragged before the user stops dragging”

  1. As it turns out, you can’t interrupt a touch gesture within the normal scope of how Android operates. It might be possible if you do serious hacking on the source code, way deep down in the Choreography class and some of the core classes, which is NOT advisable, but even then it may not work.

    What you (or I; weird answering my own question) most likely need to do is use a SurfaceView instead of the GridLayout. When you override onTouchEvent() get the X and Y coordinates of the TouchEvent (event.getX(), event.getY()) and see if those points fall within the bounding Rectangle of any of the original tiles or maze path areas (Rect.contains(x, y)). As long as the touch events are happening in the “acceptable” areas of the game board, continue to redraw the Ball object centered at the (x,y) point of the TouchEvent. As soon as you detect that the TouchEvent has occurred outside of the “acceptable” areas, either stop redrawing the Ball or set a flag on the object to indicate where the last acceptable (x,y) points were, redraw the Ball there, and flag it as “immovable” until the next TouchGesture starts.

Leave a Reply