Swipe Detector in Android

This entry is part 47 of 50 in the series Android Development Primer

If you’ve used an Android device, Swipe Detection is not new to you. Unlocking the phone, receiving calls etc. all make use of a Swipe Detector mechanism. Technically speaking, a Swipe is known as a Motion Event in Android.

In this post I will show you how to create a Swipe Detection mechanism and use it for various purposes. Start up an activity and follow along. Here I will give you the Source Code first and then go on to explain it later.

package com.nero.myfirstapp;

import android.view.MotionEvent;
import android.view.View;

public class SwipeDetector implements View.OnTouchListener{
	public static enum Action {
        LR, // Left to right
        RL, // Right to left
        TB, // Top to bottom
        BT, // Bottom to top
        None // Action not found
    }

    private static final int HORIZONTAL_MIN_DISTANCE = 80; // The minimum distance for horizontal swipe
    private static final int VERTICAL_MIN_DISTANCE = 30; // The minimum distance for vertical swipe
    private float downX, downY, upX, upY; // Coordinates
    private Action mSwipeDetected = Action.None; // Last action

    public boolean swipeDetected() {
        return mSwipeDetected != Action.None;
    }

    public Action getAction() {
        return mSwipeDetected;
    }

    /**
     * Swipe detection
     */@Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            {
                downX = event.getX();
                downY = event.getY();
                mSwipeDetected = Action.None;
                return false; // allow other events like Click to be processed
            }
        case MotionEvent.ACTION_MOVE:
            {
                upX = event.getX();
                upY = event.getY();

                float deltaX = downX - upX;
                float deltaY = downY - upY;

                // horizontal swipe detection
                if (Math.abs(deltaX) > HORIZONTAL_MIN_DISTANCE) {
                    // left or right
                    if (deltaX < 0) {

                        mSwipeDetected = Action.LR;
                        return true;
                    }
                    if (deltaX > 0) {

                        mSwipeDetected = Action.RL;
                        return true;
                    }
                } else

                // vertical swipe detection
                if (Math.abs(deltaY) > VERTICAL_MIN_DISTANCE) {
                    // top or down
                    if (deltaY < 0) {

                        mSwipeDetected = Action.TB;
                        return false;
                    }
                    if (deltaY > 0) {

                        mSwipeDetected = Action.BT;
                        return false;
                    }
                }
                return true;
            }
        }
        return false;
    }

}

Understanding the Code

  • We have created an Enum names Action which contains all possible motion events possible.
  • The method getAction() return a boolean value which determines if a motion event has been detected.
  • ACTION_DOWN : It tells the device that a pressure gesture is in motion. Read about it here. It is a short and comprehensive description
  • ACTION_MOVE : It tells the device that a pressure gesture is in motion and that a change has occurred since the beginning of the gesture. Read about it here. It is a short and comprehensive description.
  • HORIZONTAL_MIN_DISTANCE is the minimum swipe length that is required to consider the gesture a horizontal swipe. We do not want to process every click or misplaced touches to be considered a swipe.
  • VERTICAL_MIN_DISTANCE is the minimum swipe length that is required to consider the gesture a vertical swipe. We do not want to process every click or misplaced touches to be considered a swipe.
  • Now, all we need to do is simple math, to determine if the swipe is from Left to Right, Right to Left, Top to Bottom and Bottom to Top.
  • Remember that the return values depend on what type of actions you want to be detecting. In the above code I want only horizontal swipes ans hence I am returning false when a vertical swipe is detected, irrespective of whether it is Top to Bottom or Bottom to Top.

Using Swipe Detector

The Swipe Detector can be used in any module you like. Below is a code snippet that can be used with modifications as necessary.

if(swipeDetector.swipeDetected()){
					if(swipeDetector.getAction() == SwipeDetector.Action.LR){
						Toast.makeText(getApplicationContext(), "Left to Right", Toast.LENGTH_SHORT).show();
					}
					if(swipeDetector.getAction() == SwipeDetector.Action.RL){
						Toast.makeText(getApplicationContext(), "Right to Left", Toast.LENGTH_SHORT).show();
					}
Series Navigation<< Android development primer: Working with Sliding Drawers in Android – Part IIThe “Values” Folder >>

Leave a Reply

Your email address will not be published. Required fields are marked *

*

* Copy This Password *

* Type Or Paste Password Here *

44,549 Spam Comments Blocked so far by Spam Free Wordpress

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>