How to Detect Common Gestures- Detect Drag

Animation in Android
When we want to detect a subset (not all of them) of common gestures, we can use GestureDetector.SimpleOnGestureListener which is an implementation of the GestureDetector.OnGestureListener interface.
Note that if we use GestureDetector.OnGestureListener, all of the common gestures must be overrided.
GestureDetector.SimpleOnGestureListener provides an implementation for all of the on methods by returning false for all of them. Thus you can override only the methods you care about.
Whether or not you use GestureDetector.OnGestureListener, it's best practice to implement an onDown() method that returns true. This is because all gestures begin with an onDown() message. If you return false from onDown(), as GestureDetector.SimpleOnGestureListener does by default, the system assumes that you want to ignore the rest of the gesture, and the other methods of GestureDetector.OnGestureListener never get called. This has the potential to cause unexpected problems in your app. The only time you should return false from onDown() is if you truly want to ignore an entire gesture.
List of all common gestures are:
  • onDown(MotionEvent e): Notified when a tap occurs with the down MotionEvent that triggered it.
  • onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY): Notified of a fling event when it occurs with the initial on down MotionEvent and the matching up MotionEvent.
  • onLongPress(MotionEvent e): Notified when a long press occurs with the initial on down MotionEvent that trigged it.
  • onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY): Notified when a scroll occurs with the initial on down MotionEvent and the current move MotionEvent.
  • onShowPress(MotionEvent e): The user has performed a down MotionEvent and not performed a move or up yet.
  • onSingleTapUp(MotionEvent e): Notified when a tap occurs with the up MotionEvent that triggered it.

Example: Here we try to do a practice of overriding onScroll() to drag a drawable (image) inside a frame.
Create a new project with an empty template. I extend a new view called ImageBoard. To define new attributes (see also custom view in Android Apps) go to res->values->attrs (if there is not such file, you can create it: right click on the values folder and select New->values resource file then enter attrs as File name). Edit attrs.xml as below. Here we define just src attribute as a reference or color.

The ImageBoard class that is the core of this tiny project is like this.

and the activity_main.xml file is shown below.

Now just run the project and see the result which should be something like this.

Comments