Mobile for the masses: Take a swipe at it! Programming gestures in Android

Trade buttons for swipes in your Android mobile apps

Mobile users are typically distracted, busy, and ergonomically constrained, so build your mobile application UIs accordingly. Andrew Glover discusses key factors that differentiate mobile apps from web apps, then guides you through the creation of a mobile application UI that uses swipe gestures for navigation rather than button clicks.


Andrew Glover, CTO, App47

Andrew GloverAndrew Glover is a developer and mobile technology enthusiast. He's currently the CTO of App47 and is the founder of the easyb behavior-driven development (BDD) framework. He is also the co-author of three books: Continuous Integration, Groovy in Action, and Java Testing Patterns. You can keep up with Andrew by reading his blog and by following him on Twitter.

23 April 2013

Also available in Chinese Russian Japanese Vietnamese


About this series

Mobile application distribution is exploding, and so is the market for mobile development skills. This developerWorks series introduces the mobile landscape to developers who are experienced with programming but new to mobility.

Start out coding native apps in Java™ code, then expand your toolkit to include JVM languages, scripting frameworks, HTML5/CSS/JavaScript, third-party tools, and more. Step by step, you'll master the skills you need to meet virtually any mobile development scenario.

When you build a mobile app, just like building a web app, keep in mind the end (and the user). Always know the purpose of your app and how people benefit from it. What type of information will your app display, what functions will it have, and how will users access both? Give ample attention to the user experience of your mobile application to help ensure its success.

Unlike traditional GUI development for desktop or web applications, the rule for mobile apps is that less is more. When you design a mobile application interface, think simple, and think easy. Most mobile devices are small (unless you deal with a Samsung Note 4 — the biggest mobile-phone-aka-tablet that I've ever seen). That small size is an essential part of their ubiquity and is why people carry them everywhere and use them anywhere. This leads to another important observation about mobile apps, which is that most users are not focused on your app when they use it!

Some mobile apps are built specifically for tablets and just for business use cases (such as doctors who access patient records). Most mobile apps are meant to be accessed on tiny devices by users who are, frankly, also doing something else. As I wait in line to purchase some groceries, I might decide to play a few rounds of Angry Birds. If I'm about to de-plane after a long flight, I might use that time to check my email. But, if it takes me more than two taps or swipes to load up some angry birds or email messages, I'm likely to move on.

Another thing that really differentiates mobile apps from traditional web and desktop applications is quantity: For every web app, there are easily 100 mobile ones. Offer more than a worthy service with your application. Make easy and compelling to use. If you expect users to RTM (read the manual) to use your app, then you create a problem for them, which eventually becomes a problem for you. Whether your user is the doctor who accesses patient records or the person who plays Cut-the-Rope in the waiting room doesn't matter. If your mobile app takes more than a couple minutes to set up, users are likely to search the app store for one that requires less time.

(Hello) Overheard Word

If you read the first article in this new series, you learned how to set up your Android development environment in Eclipse, and you configured your Android SDK for Android version 4.2. You also developed your first basic Android app, a classic of the Hello World variety. This month you continue along that path by designing a more unique application.

My example app, Overheard Word, is intended to make it fun and easy to learn new vocabulary words and practice them in context — incidentally, two of my favorite things. In the app, users study a few words and then take a quiz. The interface consists of a display screen and two buttons. The display is for words and their corresponding definitions, while the buttons are for user navigation through the app.

Overheard Word is a fun and simple mobile application for people who love words (by which I mean vocabulary aficionados and word connoisseurs). More importantly, it serves as an example of building a legitimate Android app, which you can then deploy to a real Android device.

Targeting the app

Before I design an app, I like to evaluate my target market. The app that I built in Part 1 targeted Android 4.2, or API version 17. Look at the most current Android distributions reported by Google (see Figure 1):

Figure 1. Android distributions by version
Screen capture that shows ranked Android distributions

Tablets versus phones

In Figure 1, tablet sales most likely caused the increase of users around Android version 15. Most tablets, regardless of manufacturer, currently run Android 4.x. Unless you specifically build an Android tablet app, target your app to Android API versions 9 and 10, which currently represent most of the mobile device market.

Figure 1 shows that Android 2.3.x (API versions 9 and 10) currently represents roughly half of the Android device market! If half of all Android devices are running Android 2.3.x, doesn't it make sense to develop for that market?

Start a new project

When we left off last month, I had installed API version 4.2. Now I want to install Android 2.3.3 (API 10). When I fire up my Android SDK Manager, as in Figure 2, I also see that I have a few updates to install:

Figure 2. A local Android SDK installation with only one version installed
Screen capture of Android SDK Manager showing Android version 4.2 installed

If you want to follow along with me, click the Android 2.3.3 (API 10) installation option and keep any recommended updates that the manager indicates.

Figure 3. Installing Android 2.3.3 (API 10)
Screen capture of Android SDK Manager installing Android 2.3.3

After you download a new API for Android, you also must create a compatible emulator or Android Virtual Device (AVD). From the Android SDK Manager, select the Tools menu, then the Manage AVDs option. Be sure to create an AVD that targets API Level 10.

Figure 4. Creating an AVD
Screen capture of creating the emulator or AVD in SDK Manager

Next, create a New Android Application project and name it. My project is the Overheard Word app. Set the app's target to API 10 to make it accessible to the maximum number of devices. Look closely at the screen capture in Figure 5 and note that I also chose to compile with API 10. You can compile with a newer version of Android but I prefer to program and compile with the same API. (If I compile with a later API, I must be careful not to use any of its features in my app, which might create a compatibility issue.)

Figure 5. Creating a new Android project in Eclipse
Screen capture of creating a new Android project in Eclipse

When you click Next, be sure that you do not make your app a Library Project. Keep the same defaults that you set for the Hello World app. You can always make small changes (such as to the icon file for the app) later.

The final setup step is to name your first Activity. I call mine OverheardWord rather than Main, and I name the layout similarly. If you also use API 10 as your target version, you have a few Navigation Type choices in the final dialog. Don't worry about that for now; I show you how to create a menu for navigation in a later article. For this app, keep your Navigation Type selection as none.

Figure 6. Creating a default Activity
Screen capture of creating a default activity in Eclipse

Click Finish to create a project that looks just like the default HelloWorld project you worked on last time.

Building an Android UI

Now you're ready to build a simple UI. As you might recall, an Android UI is ultimately defined as an XML document, which you are probably familiar with. If you do traditional Java™ GUI development, you might remember layouts, which Android uses too. With Android's layouts, you can define (or suggest, really) how a device lays out your application's visual components. Layout styles include:

  • Linear, where components are organized in a horizontal or vertical fashion (similar to newspaper columns)
  • Relative, where components are spaced relative to each other (with widget 2 to the right of widget 1, and so on)
  • Table, where components are displayed in columns and rows

More layout styles are available, but three will certainly get you started!

Within a layout, you can define widgets, which are normal components that you might expect to find in any GUI. The Android platform offers basic widgets like buttons, text-boxes, and drop-down lists, and more sophisticated ones like image viewers and spin-wheels.

I already determined that my Overheard Word UI requires:

  • Three text fields (to hold a word, its part of speech, and its definition)
  • Two buttons (one to select a new word and another to take a quiz)

Define the layout

The first step to putting together an Android UI is to define its layout, along with the widgets that you want in it. In Listing 1, I first define a LinearLayout with three TextViews. Next, I create a sub-layout (another LinearLayout) holding two Buttons.

Listing 1. Defining a LinearLayout in Android
<LinearLayout xmlns:android=""
    tools:context=".OverheardWord" >

        android:textSize="30sp" />

        android:textSize="18sp" />

        android:textSize="18sp" />

        android:layout_marginRight="5dp" >

            android:text="@string/next_word" />

            android:text="@string/take_quiz" />


As you can see from the XML in Listing 1, each widget has a number of properties that ultimately affect its look and feel. For example, each of the two buttons has a text element whose string points to a resource element. That resource element is defined in a resource file named strings.xml, which is stored in the res/values directory. Listing 2 shows the strings.xml file.

Listing 2. The resource file that defines button colors and labels
<?xml version="1.0" encoding="utf-8"?>

    <string name="app_name">Overheard Word</string>

    <color name="white">#ffffff</color>
    <color name="black">#000000</color>

    <string name="next_word">Next word</string>
    <string name="take_quiz">Take quiz</string>


If I want to see what my UI looks like so far, I can start an emulator instance. Instead, I click the Graphical Layout tab in Eclipse, as in Figure 7.

Figure 7. Overheard Word running in Eclipse
Screen capture of the Overheard Word app running in Eclipse

Placeholder text

Previewing my UI, I'm slightly confused by the white space for my word attributes. That's no problem: I add some sample text for a more realistic idea of how the text displays before I write my code.

First, I add an android:text attribute to each of the TextView widgets, just like I did for my button labels. For now, I add placeholder text, like so:

Listing 3. Creating placeholders with android:text
        android:text="Part of Speech"/>

As you can see in Listing 3, I added sample text ("Part of Speech") to the word_study_part_of_speechTextView. I updated some of the styling elements by increasing the text size, defining the text color, and centering the widget in the layout. The attributes in Listing 3 are common for defining widgets in an Android application; as you build more apps, you come to know and love them. I also define the sample text directly in my layout file rather than a resource file because the text values are temporary during my design process.

When I run my app from Eclipse, I get an idea of what users will see when they start the app:

Figure 8. Overheard Word running in an AVD
Screen capture of the Overheard Word app running in an AVD

Something about the UI design still isn't right. Can you guess what it is? Yeah, it's those pesky buttons! Are they necessary? Do users normally click buttons on mobile apps? Maybe users can swipe left or right to see new words and swipe down to take a quiz.

Removing the buttons cleans up my UI and better adapts the Overheard Word app to the expectations of most mobile users. I can easily implement the swiping behavior, as you'll soon see.

Coding gestures in Android

I defined the initial screen for my Overheard Word app and I'm ready to add some behavior. My experience with traditional Java GUI development again applies directly to Android, in that I first implement listeners that respond to events. If I keep the two buttons, I might use an OnClickListener to attach behavior to each button-click action, and then attach that to the setOnClickListener method of each button widget.

Anonymous classes

Anonymous classes are classes local to a class but without a name: you can both define and instantiate anonymous classes in a single expression. I find that anonymous classes are both handy and elegant, and I write them a lot, especially when programming user-interface behavior.

While I certainly can use OnClickListener, I'm likely to end up with multiple class files for more than one widget. I don't like all that clutter, so I prefer the alternative implementation strategy of anonymous classes.

Even though a gesture like swipe isn't a notion in traditional GUI programming, its implementation is similar to coding a button click. I start a touch listener, which is part of the underlying Android platform, and then provide corresponding behavior. To detect a finger-swiping motion, I also calculate the difference between the start and end of a gesture, plus the speed of the swipe. (I find it helpful, here, to think of Cartesian coordinates: left and right swipes are on the X axis, while up and down are on the Y axis.)

A gesture can happen anywhere on an interface. When you attach this sort of listener to any component of an app's interface, start with the layout (which is represented as a View in Android) and include the simplest button widget. I use Android's SimpleOnGestureListener to create my initial gesture implementation, then attach it to my View through its onTouchListener method. By attaching to an instance of my view, I can detect the swipe across the entire interface and not just within a component of it, such as a small picture viewer.

Before I do that, though, I must write a class that can detect finger movements on a mobile device.

The SwipeDetector

Button clicks are relatively easy to detect. The underlying operating system usually abstracts the coordinate details of the button's boundaries, so you can skip manually defining them. Programming your app to recognize and respond to a swiping motion is a bit more intricate. Android leaves a lot up to the programmer, so the job is slightly more involved but also gives you tremendous flexibility. You might choose to detect a single swipe as I do here. You also might detect other finger movements, such as the rubbing motions sometimes used for games.

Thinking mobile

Isn't it curious that a mobile app listener is still defined by the verb click? Last time that I checked, users press buttons on their mobile devices rather than click them like they do with a desktop mouse. Part of becoming a mobile developer involves thinking in terms of mobility, which means you rethink traditional web and desktop mechanisms like button clicks, start menus, and even GUI wizards.

Programming swipe detection involves some Cartesian math. Namely, if the start coordinate on the X axis of the touch minus the end coordinate on the same axis is greater than a pre-determined distance, and if the velocity of that motion is greater than some other predetermined value, then you can reasonably assume that the user swiped a finger from the right side of your app display to the left. Up and down swipes are similarly calculated on the Y axis.

I can easily abstract this sort of logic into a simple class that does the elementary math for me. The SimpleOnGestureListener has a method that is called onFling. The onFling method takes two MotionEvent types (for start and end)to represent the X velocities and two floats to represent the Y velocities. The SwipeDetector class in Listing 4 thus has four methods that delineate a swipe's full range of motion: left, right, up, and down.

Listing 4. The SwipeDetector
import android.view.MotionEvent;

public class SwipeDetector {

    private int swipe_distance;
    private int swipe_velocity;
    private static final int SWIPE_MIN_DISTANCE = 120;
    private static final int SWIPE_THRESHOLD_VELOCITY = 200;

    public SwipeDetector(int distance, int velocity) {
        this.swipe_distance = distance;
        this.swipe_velocity = velocity;

    public SwipeDetector() {
        this.swipe_distance = SWIPE_MIN_DISTANCE;
        this.swipe_velocity = SWIPE_THRESHOLD_VELOCITY;

    public boolean isSwipeDown(MotionEvent e1, MotionEvent e2, float velocityY) {
        return isSwipe(e2.getY(), e1.getY(), velocityY);

    public boolean isSwipeUp(MotionEvent e1, MotionEvent e2, float velocityY) {
        return isSwipe(e1.getY(), e2.getY(), velocityY);

    public boolean isSwipeLeft(MotionEvent e1, MotionEvent e2, float velocityX) {
        return isSwipe(e1.getX(), e2.getX(), velocityX);

    public boolean isSwipeRight(MotionEvent e1, MotionEvent e2, float velocityX) {
        return isSwipe(e2.getX(), e1.getX(), velocityX);

    private boolean isSwipeDistance(float coordinateA, float coordinateB) {
        return (coordinateA - coordinateB) > this.swipe_distance;

    private boolean isSwipeSpeed(float velocity) {
        return Math.abs(velocity) > this.swipe_velocity;

    private boolean isSwipe(float coordinateA, float coordinateB, float velocity) {
        return isSwipeDistance(coordinateA, coordinateB)
                && isSwipeSpeed(velocity);

Now that I have a handy class to tell me whether a particular gesture occurs, I can plug it into my UI. Recall that I first created a default Activity, which I named OverheardWord. I leave all the default code that Eclipse gave me, but I'm going to add a few more things. To listen and respond to swipes, I define Android's GestureDetector, which takes an implementation of an OnGestureListener. Thankfully, the Android team created a convenience class that I can implement through an anonymous class dubbed SimpleOnGestureListener. Then, I override the onFling method.

Swipe detection in the UI

In my Activity's onCreate method, I start creating an GestureDetector with a SimpleOnGestureListener, which uses my SwipeDetector class.

My next step is to write a small dialog to indicate that an event fired when someone swipes. This type of small, short-lived dialog in Android is called a Toast. A Toast can, in some cases, consist of just one line of code.

Listing 5. GestureDetector
private GestureDetector initGestureDetector() {
    return new GestureDetector(new SimpleOnGestureListener() {
        private SwipeDetector detector = new SwipeDetector();
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, 
               float velocityY) {
            try {
                if (detector.isSwipeDown(e1, e2, velocityY)) {
                    return false;
                } else if (detector.isSwipeUp(e1, e2, velocityY)) {
                    showToast("Up Swipe");
                }else if (detector.isSwipeLeft(e1, e2, velocityX)) {
                    showToast("Left Swipe");
                } else if (detector.isSwipeRight(e1, e2, velocityX)) {
                    showToast("Right Swipe");
            } catch (Exception e) {} //for now, ignore
            return false;
        private void showToast(String phrase){
            Toast.makeText(getApplicationContext(), phrase, Toast.LENGTH_SHORT).show();

Now I've created an initGestureDetector method that calculates the range and velocity of a user's swipe. First, it creates an anonymous instance of SimpleOnGestureListener and provides an implementation of the onFling method. Note how the onFling method uses the SwipeDetector. For example, if a match occurs on an upward swipe, a Toast displays to indicate the movement.

My next step is to plug the swipe detection behavior into my UI. I start by registering a few listeners with an instance of the View.

Listing 6. Registering swipe detection on a View
private GestureDetector gestureDetector;

protected void onCreate(Bundle savedInstanceState) {

    gestureDetector = initGestureDetector();

    View view = findViewById(;

    view.setOnTouchListener(new View.OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            return gestureDetector.onTouchEvent(event);

    view.setOnClickListener(new OnClickListener() {
        public void onClick(View arg0) {

In my onCreate method, I got a handle to the actual View instance through its Id. Most Java developers appreciate this handy Android-ism.

The find view by ID method

Remember when I defined the XML for my UI, along with corresponding values in various resource files (like the strings.xml)? When I compile my Android app, that XML turns into generated code and is given corresponding Ids in a class called R. Check out the R class in your project's gen directory before you go any further.

Look at your layout XML file (you might recall that I named mine activity_overheard_word.xml). In that XML file, every widget has an id attribute. For instance, the id of my app's layout is android:id="@+id/LinearLayout1", or LinearLayout1 for short. The Id name is automatically generated by Eclipse but I can change it if I want. What's important is that the id, LinearLayout1, has a corresponding property in the R class, as in Listing 7.

Listing 7. Widget IDs in the R class
public static final class id {
    public static final int LinearLayout1=0x7f090000;
    public static final int action_settings=0x7f090004;
    public static final int word_study_definition=0x7f090003;
    public static final int word_study_part_of_speech=0x7f090002;
    public static final int word_study_word=0x7f090001;

By combining the content of an XML file with its corresponding R file, I can reference widgets without having to parse XML. So returning to my Activity's onCreate method, I can get a reference to the View widget through its id: The findViewById method is provided by the Android platform when you extend Activity.

Finger swiping good!

After I have the View instance, I can attach my gestureDetector instance through the setOnTouchListener. In Listing 6, another anonymous class now handles all of my touch behavior. When a user touches the device screen, this event fires and defers to my gestureDetector. I also implement an OnClickListener and set it in the setOnClickListener method; but in this case the anonymous class has no behavior.

And with all of that, I have a rather uncomplicated interface that responds to finger swipes. In this case, three of them: left, right, and up. Try this code in your AVD. To simulate a swipe, click with your mouse and drag it left, right, or up.

Now, how about running this app-in-progress on a real-life device?

Deploying in development

In response to the proliferation of viruses, Trojan horses, and malware that plague unsuspecting users, both Apple and Google introduced a form of code signing for third-party apps that runs on their respective devices. In theory, code signing serves as insurance that someone reputable built the app and that no one tampered with the binary file before you installed it. In practice, the Google and Apple codes for signing security are different. When I sign my Android app, for instance, I can claim that I am a well-known national bank. I cannot do that when I sign my app for iOS or Windows Phone 8.

In development mode, code signing is not a worry. In fact, Android and Eclipse build a binary signed with a developer key that is unknown to you. So getting an app onto a device isn't difficult in development mode. The easiest way to get such an app onto your device is to plug your Android device into your computer's USB port.

Next, go into Eclipse, right-click on your project, and select the Run As menu option, followed by Run Configurations. Eclipse displays a configurations dialog where you can select your project and click the Target tab, as in Figure 9.

Figure 9. Selecting a device to run your app on
Screen capture of selecting a device in Eclipse

You can choose Always prompt to pick device (if you want to be selective) or Launch on all compatible devices/AVD's. If you choose the latter, select the Active Devices option as I did, then click Run. In a few moments, assuming that you coded along with me, a nifty app displays on your device. Swipe left, right, and up, and witness the simple dialogs that confirm everything works.

Security settings

If you cannot load your app from email or Dropbox, go into your device's settings screen and enable Unknown Sources under Security Settings. With that change, you can install apps not from Google Play, including your app-in-progress.

Another way to deploy your development app is to email its .apk file to yourself, then open it up on your Android device and follow the automatic installation dialog. Or you might upload the .apk file to a service like Dropbox, then open up Dropbox on your device and install from there. The .apk file for your app is in your project's bin directory, where Eclipse also puts the corresponding binary.

Keep in mind that these deployment mechanisms are for development testing and not distribution purposes. To distribute and make money from your app involve several more steps, which I'll discuss in a future article.

In conclusion

Designing a mobile app means thinking simple, and thinking easy. This month you learned how to program a mobile app to respond to swipe gestures rather than the button clicks typical for desktop and web users. In some cases, a mobile app might benefit from a handy button or two. Make sure they're appropriate to the user's goal. I didn't need buttons for my super simple Overheard Word app, and the up-and-down swipe navigation I worked out is intuitive for most mobile app users.

I covered mobile application deployment quickly here but only went as deep as testing — you have yet to deploy a production app. Most users do not install untrusted apps, which is why most successful apps are distributed by an intermediary such as Google Play, iTunes App Store, or Amazon Appstore for Android. In a future article, I walk through the process of meeting an app store's security standards. That process goes quite a few steps beyond just signing your application. The important thing, though, is that after your app is hosted by a major distributor, it becomes available to the entire world.



Get products and technologies

  • Download Android: The Android SDK provides you the API libraries and developer tools necessary to build, test, and debug apps for Android.
  • Download IBM developer kits: Update your system and get the latest tools and technologies here.


  • The developerWorks community: Connect with other developerWorks users as you explore the developer-driven blogs, forums, groups, and wikis.


developerWorks: Sign in

Required fields are indicated with an asterisk (*).

Need an IBM ID?
Forgot your IBM ID?

Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.


All information submitted is secure.

Dig deeper into Java technology on developerWorks

Zone=Java technology, Mobile development, Open source
ArticleTitle=Mobile for the masses: Take a swipe at it! Programming gestures in Android