Working with Gestures
Android devices often rely on touchscreens for user input. Users are now quite comfortable using common finger gestures to operate their devices. Android applications can detect and react to one-finger (single-touch) and two-finger (multitouch) gestures. Users can also use gestures with the drag-and-drop framework to enable the arrangement of View controls on a device screen.
One of the reasons that gestures can be a bit tricky is that a gesture can be made of multiple touch events or motions. Different sequences of motion add up to different gestures. For example, a fling gesture involves the user pressing a finger down on the screen, swiping across the screen, and lifting the finger up off the screen while the swipe is still in motion (that is, without slowing down to stop before lifting the finger). Each of these steps can trigger motion events to which applications can react.
Detecting User Motions within a View
By now you’ve come to understand that Android application user interfaces are built using different types of View controls. Developers can handle gestures much as they do click events within a View control using the setOnClickListener() and setOnLong ClickListener() methods. Instead, the onTouchEvent() callback method is used to detect that some motion has occurred within the View region.
The onTouchEvent() callback method has a single parameter, a MotionEvent object. The MotionEvent object contains all sorts of details about what kind of motion occurs in the View, enabling the developer to determine what sort of gesture is happening by collecting and analyzing many consecutive MotionEvent objects. You can use all of the MotionEvent data to recognize and detect every kind of gesture you can possibly imagine. Alternatively, you can use built-in gesture detectors provided in the Android SDK to detect common user motions in a consistent fashion. Android currently has two different classes that can detect navigational gestures:
- The GestureDetector class can be used to detect common single-touch gestures.
- The ScaleGestureDetector can be used to detect multitouch scale gestures.
It is likely that more gesture detectors will be added in future versions of the Android SDK. You can also implement your own gesture detectors to detect any gestures not supported by the built-in ones. For example, you might want to create a two-fingered rotate gesture to, say, rotate an image, or a three-fingered swipe gesture that brings up an options menu.
In addition to common navigational gestures, you can use the android.gesture package with the GestureOverlayView to recognize commandlike gestures. For instance, you can create an S-shaped gesture that brings up a search or a zigzag gesture that clears the screen on a drawing app. Tools are available for recording and creating libraries of this style of gesture. As it uses an overlay for detection, it isn’t well suited for all types of applications. This package was introduced in API Level 4.
Handling Common Single-Touch Gestures
Introduced in API Level 1, the GestureDetector class can be used to detect gestures made by a single finger. Some common single-finger gestures supported by the GestureDetector class include:
- onDown: Called when the user first presses the touchscreen.
- onShowPress: Called after the user first presses the touchscreen but before lifting the finger or moving it around on the screen; used to visually or audibly indicate that the press has been detected.
- onSingleTapUp: Called when the user lifts up (using the up MotionEvent) from the touchscreen as part of a single-tap event.
- onSingleTapConfirmed: Called when a single-tap event occurs.
- onDoubleTap: Called when a double-tap event occurs.
- onDoubleTapEvent: Called when an event within a double-tap gesture occurs, including any down, move, or up MotionEvent.
- onLongPress: Similar to onSingleTapUp, but called if the user holds down a finger long enough to not be a standard click but also without any movement.
- onScroll: Called after the user presses and then moves a finger in a steady motion before lifting the finger. This is commonly called dragging.
- onFling: Called after the user presses and then moves a finger in an accelerating motion before lifting it. This is commonly called a flick gesture and usually results in some motion continuing after the user lifts the finger.
You can use the interfaces available with the GestureDetector class to listen for specific gestures such as single and double taps (see GestureDetector.OnDoubleTapListener), as well as scrolls and flings (see the documentation for GestureDetector.OnGestureListener). The scrolling gesture involves touching the screen and moving a finger around on it. The fling gesture, on the other hand, causes (though not automatically) the object to continue to move even after the finger has been lifted from the screen. This gives the user the impression of throwing or flicking the object around on the screen.
Let’s look at a simple example. Let’s assume you have a game screen that enables the user to perform gestures to interact with a graphic on the screen. We can create a custom View class called GameAreaView that can dictate how a bitmap graphic moves around within the game area based upon each gesture. The GameAreaView class can use the onTouchEvent() method to pass along MotionEvent objects to a GestureDetector. In this way, the GameAreaView can react to simple gestures, interpret them, and make the appropriate changes to the bitmap, including moving it from one location to another on the screen.
In this case, the GameAreaView class interprets gestures as follows:
- A double-tap gesture causes the bitmap graphic to return to its initial position.
- A scroll gesture causes the bitmap graphic to “follow” the motion of the finger.
- A fling gesture causes the bitmap graphic to “fly” in the direction of the fling.
To make these gestures work, the GameAreaView class needs to include the appropriate gesture detector, which triggers any operations upon the bitmap graphic. Based upon the specific gestures detected, the GameAreaView class must perform all translation animations and other graphical operations applied to the bitmap. To wire up the GameAreaView class for gesture support, we need to implement several important methods:
- The class constructor must initialize any gesture detectors and bitmap graphics.
- The onTouchEvent() method must be overridden to pass the MotionEvent data to the gesture detector for processing.
- The onDraw() method must be overridden to draw the bitmap graphic in the appropriate position at any time.
- Various methods are needed to perform the graphics operations required to make a bitmap move around on the screen, fly across the screen, and reset its location based upon the data provided by the specific gesture.
All these tasks are handled by our GameAreaView class definition:
public class GameAreaView extends View { private static final String DEBUG_TAG = "SimpleGestures->GameAreaView"; private GestureDetector gestures; private Matrix translate; private Bitmap droid; private Matrix animateStart; private Interpolator animateInterpolator; private long startTime; private long endTime; private float totalAnimDx; private float totalAnimDy; public GameAreaView(Context context, int iGraphicResourceId) { super(context); translate = new Matrix(); GestureListener listener = new GestureListener(this); gestures = new GestureDetector(context, listener, null, true); droid = BitmapFactory.decodeResource(getResources(), iGraphicResourceId); } @Override public boolean onTouchEvent(MotionEvent event) { boolean retVal = false; retVal = gestures.onTouchEvent(event); return retVal; } @Override protected void onDraw(Canvas canvas) { Log.v(DEBUG_TAG, "onDraw"); canvas.drawBitmap(droid, translate, null); } public void onResetLocation() { translate.reset(); invalidate(); } public void onMove(float dx, float dy) { translate.postTranslate(dx, dy); invalidate(); } public void onAnimateMove(float dx, float dy, long duration) { animateStart = new Matrix(translate); animateInterpolator = new OvershootInterpolator(); startTime = android.os.SystemClock.elapsedRealtime(); endTime = startTime + duration; totalAnimDx = dx; totalAnimDy = dy; post(new Runnable() { @Override public void run() { onAnimateStep(); } }); } private void onAnimateStep() { long curTime = android.os.SystemClock.elapsedRealtime(); float percentTime = (float) (curTime - startTime) / (float) (endTime - startTime); float percentDistance = animateInterpolator .getInterpolation(percentTime); float curDx = percentDistance * totalAnimDx; float curDy = percentDistance * totalAnimDy; translate.set(animateStart); onMove(curDx, curDy); if (percentTime < 1.0f) { post(new Runnable() { @Override public void run() { onAnimateStep(); } }); } } }
As you can see, the GameAreaView class keeps track of where the bitmap graphic should be drawn at any time. The onTouchEvent() method is used to capture motion events and pass them along to a gesture detector whose GestureListener we must implement as well (more on this in a moment). Typically, each method of the GameAreaView applies some operation to the bitmap graphic and then calls the invalidate() method, forcing the View to be redrawn.
Now we turn our attention to the methods required to implement specific gestures:
- For double-tap gestures, we implement a method called onResetLocation() to draw the bitmap graphic in its original location.
- For scroll gestures, we implement a method called onMove() to draw the bitmap graphic in a new location. Note that scrolling can occur in any direction—it simply refers to a finger swipe on the screen.
- For fling gestures, things get a little tricky. To animate motion on the screen smoothly, we used a chain of asynchronous calls and a built-in Android interpolator to calculate the location in which to draw the graphic based upon how long it has been since the animation started. See the onAnimateMove() and onAnimateStep() methods for the full implementation of fling animation.
Now we need to implement our GestureListener class to interpret the appropriate gestures and call the GameAreaView methods we just implemented. Here’s an implementation of the GestureListener class that our GameAreaView class can use:
private class GestureListener extends GestureDetector.SimpleOnGestureListener { GameAreaView view; public GestureListener(GameAreaView view) { this.view = view; } @Override public boolean onDown(MotionEvent e) { return true; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, final float velocityX, final float velocityY) { final float distanceTimeFactor = 0.4f; final float totalDx = (distanceTimeFactor * velocityX / 2); final float totalDy = (distanceTimeFactor * velocityY / 2); view.onAnimateMove(totalDx, totalDy, (long) (1000 * distanceTimeFactor)); return true; } @Override public boolean onDoubleTap(MotionEvent e) { view.onResetLocation(); return true; } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { view.onMove(-distanceX, -distanceY); return true; } }
Note that you must return true for any gesture or motion event that you want to detect. Therefore, you must return true in the onDown() method as it happens at the beginning of a scroll-type gesture. Most of the implementation of the GestureListener class methods involves our interpretation of the data for each gesture. For example:
- We react to double taps by resetting the bitmap to its original location using the onResetLocation() method of our GameAreaView class.
- We use the distance data provided in the onScroll() method to determine the direction to use in the movement to pass in to the onMove() method of the GameAreaView class.
- We use the velocity data provided in the onFling() method to determine the direction and speed to use in the movement animation of the bitmap. The timeDistanceFactor variable with a value of 0.4 is subjective; it gives the resulting slide-to-a-stop animation enough time to be visible but is short enough to be controllable and responsive. You can think of it as a high-friction surface. This information is used by the animation sequence implemented in the onAnimateMove() method of the GameAreaView class.
Now that we have implemented the GameAreaView class in its entirety, you can display it on a screen. For example, you might create an Activity that has a user interface with a FrameLayout control and add an instance of a GameAreaView using the addView() method. Figure 8.3 shows a gesture example of dragging a droid around a screen.
Figure 8.3 Using gestures to drag the droid around the screen.
Handling Common Multitouch Gestures
Introduced in API Level 8 (Android 2.2), the ScaleGestureDetector class can be used to detect two-fingered scale gestures. The scale gesture enables the user to move two fingers toward and away from each other. Moving the fingers apart is considered scaling up; moving the fingers together is considered scaling down. This is the “pinch-to-zoom” style often employed by map and photo applications.
Let’s look at another example. Again, we use the custom View class called GameAreaView, but this time we handle the multitouch scale event. In this way, the GameAreaView can react to scale gestures, interpret them, and make the appropriate changes to the bitmap, including growing or shrinking it on the screen.
To handle scale gestures, the GameAreaView class needs to include the appropriate gesture detector, a ScaleGestureDetector. The GameAreaView class needs to be wired up for scale gesture support similarly to the single-touch gestures implemented earlier, including initializing the gesture detector in the class constructor, overriding the onTouchEvent() method to pass the MotionEvent objects to the gesture detector, and overriding the onDraw() method to draw the View appropriately as necessary. We also need to update the GameAreaView class to keep track of the bitmap graphic size (using a Matrix) and provide a helper method for growing or shrinking the graphic. Here is the new implementation of the GameAreaView class with scale gesture support:
public class GameAreaView extends View { private ScaleGestureDetector multiGestures; private Matrix scale; private Bitmap droid; public GameAreaView(Context context, int iGraphicResourceId) { super(context); scale = new Matrix(); GestureListener listener = new GestureListener(this); multiGestures = new ScaleGestureDetector(context, listener); droid = BitmapFactory.decodeResource(getResources(), iGraphicResourceId); } public void onScale(float factor) { scale.preScale(factor, factor); invalidate(); } @Override protected void onDraw(Canvas canvas) { Matrix transform = new Matrix(scale); float width = droid.getWidth() / 2; float height = droid.getHeight() / 2; transform.postTranslate(-width, -height); transform.postConcat(scale); transform.postTranslate(width, height); canvas.drawBitmap(droid, transform, null); } @Override public boolean onTouchEvent(MotionEvent event) { boolean retVal = false; retVal = multiGestures.onTouchEvent(event); return retVal; } }
As you can see, the GameAreaView class keeps track of what size the bitmap should be at any time using the Matrix variable called scale. The onTouchEvent() method is used to capture motion events and pass them along to a ScaleGestureDetector gesture detector. As before, the onScale() helper method of the GameAreaView applies some scaling to the bitmap graphic and then calls the invalidate() method, forcing the View to be redrawn.
Now let’s take a look at the GestureListener class implementation necessary to interpret the scale gestures and call the GameAreaView methods we just implemented. Here’s the implementation of the GestureListener class:
private class GestureListener implements ScaleGestureDetector.OnScaleGestureListener { GameAreaView view; public GestureListener(GameAreaView view) { this.view = view; } @Override public boolean onScale(ScaleGestureDetector detector) { float scale = detector.getScaleFactor(); view.onScale(scale); return true; } @Override public boolean onScaleBegin(ScaleGestureDetector detector) { return true; } @Override public void onScaleEnd(ScaleGestureDetector detector) { } }
Remember that you must return true for any gesture or motion event that you want to detect. Therefore, you must return true in the onScaleBegin() method as it happens at the beginning of a scale-type gesture. Most of the implementation of the GestureListener methods involves our interpretation of the data for the scale gesture. Specifically, we use the scale factor (provided by the getScaleFactor() method) to calculate whether we should shrink or grow the bitmap graphic, and by how much. We pass this information to the onScale() helper method we just implemented in the GameAreaView class.
Now, if you were to use the GameAreaView class in your application, scale gestures might look something like Figure 8.4.
Figure 8.4 The result of scale-down (left) and scale-up (right) gestures.
Making Gestures Look Natural
Gestures can enhance your Android application user interfaces in new, interesting, and intuitive ways. Closely mapping the operations being performed on the screen to the user’s finger motion makes a gesture feel natural and intuitive. Making application operations look natural requires some experimentation on the part of the developer. Keep in mind that devices vary in processing power, and this might be a factor in making things seem natural. Minimal processing, even on fast devices, will help keep gestures and the reaction to them smooth and responsive, and thus natural-feeling.
Using the Drag-and-Drop Framework
On Android devices running Android 3.0 and higher (API Level 11), developers can access the drag-and-drop framework to perform drag-and-drop actions. You can drag and drop View controls within the scope of a screen or Activity class.
The drag-and-drop process basically works like this:
- The user triggers a drag operation. How this is done depends on the application, but long clicks are a reasonable option for selecting a View for a drag under the appropriate conditions.
- The data for the selected View control is packaged in a ClipData object (also used by the clipboard framework), and the View.DragShadowBuilder class is used to generate a little visual representation of the item being dragged. For example, if you were dragging a filename into a directory bucket, you might include a little icon of a file.
- You call the startDrag() method on the View control to be dragged. This starts a drag event. The system signals a drag event with ACTION_DRAG_STARTED, which listeners can catch.
- There are a number of events that occur during a drag that your application can react to. The ACTION_DRAG_ENTERED event can be used to adjust the screen controls to highlight other View controls that the dragged View control might want to be dragged over to. The ACTION_DRAG_LOCATION event can be used to determine where the dragged View is on the screen. The ACTION_DRAG_EXITED event can be used to reset any screen controls that were adjusted in the ACTION_DRAG_ENTERED event.
- When the user ends the drag operation by releasing the shadow item over a specific target View on the screen, the system signals a drop event with ACTION_DROP, which listeners can catch. Any data can be retrieved using the getClipData() method.
For more information about the drag-and-drop framework, see the Android SDK documentation. There you can also find a great example of using the drag-and-drop framework called DragAndDropDemo.java.