How To Detect Swipe Gesture Direction In Android

This example will tell you how to check and display swipe gesture direction in the android application. It also shows how to know whether the user single-tap or double-taps the android device screen. If you want to know basic knowledge about how to listen and respond to user gestures in the android app, please read the article How To Detect Common Android Gestures

1. Detect Swipe Gesture Direction Example.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/GAkWcd9Ji3o

  1. There is a TextView object in the example.
  2. When the user swipe on, single tap, or double-tap the screen, it will show related text in the TextView.
  3. And only the swipe distance between special values can make the swipe action take effect.

2. Main Activity Java Class.

  1. DetectSwipeDirectionActivity.java
  2. This activity file is saved in the app/java folder.
    package com.dev2qa.gestureexample;
    
    import android.os.Bundle;
    import android.support.v4.view.GestureDetectorCompat;
    import android.support.v7.app.AppCompatActivity;
    import android.view.MotionEvent;
    import android.widget.TextView;
    
    public class DetectSwipeDirectionActivity extends AppCompatActivity {
    
        // This textview is used to display swipe or tap status info.
        private TextView textView = null;
    
        // This is the gesture detector compat instance.
        private GestureDetectorCompat gestureDetectorCompat = null;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_detect_swipe_direction);
    
            setTitle("dev2qa.com - Detect Android Swipe Direction Example.");
    
            // Get the text view.
            textView = (TextView)findViewById(R.id.detect_swipe_direction_textview);
    
            // Create a common gesture listener object.
            DetectSwipeGestureListener gestureListener = new DetectSwipeGestureListener();
    
            // Set activity in the listener.
            gestureListener.setActivity(this);
    
            // Create the gesture detector with the gesture listener.
            gestureDetectorCompat = new GestureDetectorCompat(this, gestureListener);
        }
    
        @Override
        public boolean onTouchEvent(MotionEvent event) {
            // Pass activity on touch event to the gesture detector.
            gestureDetectorCompat.onTouchEvent(event);
            // Return true to tell android OS that event has been consumed, do not pass it to other event listeners.
            return true;
        }
    
        public void displayMessage(String message)
        {
            if(textView!=null)
            {
                // Display text in the text view.
                textView.setText(message);
            }
        }
    }

3. Swipe Gesture Listener Java Class.

  1. DetectSwipeGestureListener.java
  2. Saved in app/java folder.
    package com.dev2qa.gestureexample;
    
    import android.view.GestureDetector;
    import android.view.MotionEvent;
    
    public class DetectSwipeGestureListener extends GestureDetector.SimpleOnGestureListener {
    
        // Minimal x and y axis swipe distance.
        private static int MIN_SWIPE_DISTANCE_X = 100;
        private static int MIN_SWIPE_DISTANCE_Y = 100;
    
        // Maximal x and y axis swipe distance.
        private static int MAX_SWIPE_DISTANCE_X = 1000;
        private static int MAX_SWIPE_DISTANCE_Y = 1000;
    
        // Source activity that display message in text view.
        private DetectSwipeDirectionActivity activity = null;
    
        public DetectSwipeDirectionActivity getActivity() {
            return activity;
        }
    
        public void setActivity(DetectSwipeDirectionActivity activity) {
            this.activity = activity;
        }
    
        /* This method is invoked when a swipe gesture happened. */
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
    
            // Get swipe delta value in x axis.
            float deltaX = e1.getX() - e2.getX();
    
            // Get swipe delta value in y axis.
            float deltaY = e1.getY() - e2.getY();
    
            // Get absolute value.
            float deltaXAbs = Math.abs(deltaX);
            float deltaYAbs = Math.abs(deltaY);
    
            // Only when swipe distance between minimal and maximal distance value then we treat it as effective swipe
            if((deltaXAbs >= MIN_SWIPE_DISTANCE_X) && (deltaXAbs <= MAX_SWIPE_DISTANCE_X))
            {
                if(deltaX > 0)
                {
                    this.activity.displayMessage("Swipe to left");
                }else
                {
                    this.activity.displayMessage("Swipe to right");
                }
            }
    
            if((deltaYAbs >= MIN_SWIPE_DISTANCE_Y) && (deltaYAbs <= MAX_SWIPE_DISTANCE_Y))
            {
                if(deltaY > 0)
                {
                    this.activity.displayMessage("Swipe to up");
                }else
                {
                    this.activity.displayMessage("Swipe to down");
                }
            }
    
    
            return true;
        }
    
        // Invoked when single tap screen.
        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            this.activity.displayMessage("Single tap occurred.");
            return true;
        }
    
        // Invoked when double tap screen.
        @Override
        public boolean onDoubleTap(MotionEvent e) {
            this.activity.displayMessage("Double tap occurred.");
            return true;
        }
    }

4. Main Layout Xml File.

  1. activity_detect_swipe_direction.xml
  2. This XML file is saved in the app/res/layout folder.
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:gravity="center">
    
        <TextView
            android:id="@+id/detect_swipe_direction_textview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="20dp"
            android:textAllCaps="false"
            android:text="Swipe on the screen to see my text changed."/>
    
    </LinearLayout>

5. Android Manifest Xml File.

  1. AndroidManifest.xml
  2. Saved in app/manifests folder.
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.dev2qa.gestureexample">
    
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
           
            <activity android:name=".DetectSwipeDirectionActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>
    
    </manifest>
0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Cobalt2009
Cobalt2009

Good code, thanks

Gabriel Gongora
Gabriel Gongora

I use en Main activity, but i trie use en SecondActivity

error: incompatible types: Detalle_Cuenta cannot be converted to MainActivity

How use this class in second Activity?

2
0
Would love your thoughts, please comment.x
()
x