How To Detect Common Android Gestures

We all know that you can use gestures in the android app. And there are a lot of common gestures such as tap down, tap up, scroll, double-tap, swipe from left to right or right to left ( also called fling ), etc. But how to detect those gestures in your android application source code? This article will tell you how to do.

1. How To Detect Gestures In Android Activity And View Object?

  1. Create a custom gesture listener class which extends android.view.GestureDetector.SimpleOnGestureListener.
  2. You can also make your custom class implements interface android.view.GestureDetector.OnGestureListener or GestureDetector.OnDoubleTapListener or GestureDetector.OnContextClickListener.
  3. But the SimpleOnGestureListener class has already implemented those three interfaces.
  4. Override the methods in SimpleOnGestureListener which you want to execute when according gestures event happened.
  5. Create an instance of the above custom gestures listener class.
  6. Create an instance of android.support.v4.view.GestureDetectorCompat, use the custom gesture listener instance as the input parameter.
  7. Invoke GestureDetectorCompat instance’s onTouchEvent method in activity’s onTouchEvent method to make the activity listen and catch user gestures.
  8. Invoke GestureDetectorCompat instance’s onTouchEvent method in view object’s OnTouchListener‘s onTouch method to make the view object listen and catch user gestures.

2. Detect Common Android Gestures Example.

  1. Create a new android project with the Empty Activity template.
  2. Create a custom class CommonGestureListener extends GestureDetector.SimpleOnGestureListener. This class has a private instance filed srcView to identify which view this gesture listener is listening on.
  3. Override gesture listener’s methods and print debug log in android studio Logcat console.
  4. Add an image view in the main activity class.
  5. In the main activity class, create two instances of GestureDetectorCompat class use the instance of CommonGestureListener.
  6. One GestureDetectorCompat object is used in activity’s onTouchEvent method, another object is used in ImageView‘s OnTouchListener‘s onTouch method.
  7. Below are the related java, layout, and image files in this example.
    C:\WORKSPACE\WORK\DEV2QA.COM-EXAMPLE-CODE\ANDROIDEXAMPLEPROJECT\GESTUREEXAMPLE
    │   .gitignore
    │   build.gradle
    │   gesture.txt
    │   gradle.properties
    │   gradlew
    │   gradlew.bat
    │   settings.gradle
    │
    ├───.idea
    │       gradle.xml
    │       misc.xml
    │       modules.xml
    │       runConfigurations.xml
    │
    ├───app
    │   │   .gitignore
    │   │   build.gradle
    │   │   proguard-rules.pro
    │   │
    │   └───src
    │       ├───androidTest
    │       │   └───java
    │       │       └───com
    │       │           └───dev2qa
    │       │               └───gestureexample
    │       │                       ExampleInstrumentedTest.java
    │       │
    │       ├───main
    │       │   │   AndroidManifest.xml
    │       │   │
    │       │   ├───java
    │       │   │   └───com
    │       │   │       └───dev2qa
    │       │   │           └───gestureexample
    │       │   │               │   CommonGestureListener.java
    │       │   │               │   MainActivity.java
    │       │   │
    │       │   └───res
    │       │       ├───drawable
    │       │       │       green_button.jpg
    │       │       ├───layout
    │       │       │       activity_main.xml
    │       │       │
    │       │       ├───raw
    │       │       │       gesture.txt
    │       │       │
    │       │       └───values
    │       │               colors.xml
    │       │               strings.xml
    │       │               styles.xml
    │       │
    │       └───test
    │           └───java
    │               └───com
    │                   └───dev2qa
    │                       └───gestureexample
    │                               ExampleUnitTest.java
    │
    └───gradle
        └───wrapper
                gradle-wrapper.jar
                gradle-wrapper.properties
  8. When executing this example and make different gestures on the image view or activity screen, you can see the below log console output.
    detect-common-android-gestures-logcat-output

3. Main Activity Java File.

  1. MainActivity.java
    package com.dev2qa.gestureexample;
    
    import android.support.v4.view.GestureDetectorCompat;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.MotionEvent;
    import android.view.View;
    import android.widget.ImageView;
    
    public class MainActivity extends AppCompatActivity {
    
        // This gesture detector is used in activity's onTouchEvent method.
        private GestureDetectorCompat activityGestureDetectorCompat = null;
    
        // This gesture detector is used in image view's onTouchListener's onTouch method.
        private GestureDetectorCompat imageViewGestureDetectorCompat = null;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            setTitle("dev2qa.com - Android Gesture Example.");
    
            // Get the image view.
            ImageView imageView = (ImageView)findViewById(R.id.common_gesture_imageview);
    
            if(activityGestureDetectorCompat==null)
            {
                // Create a custom gesture listener.
                CommonGestureListener activityGestureListener = new CommonGestureListener();
    
                // Set source view object.
                activityGestureListener.setSrcView(null);
    
                // Create activity gesture detector object use activity gesture listener.
                activityGestureDetectorCompat = new GestureDetectorCompat(this, activityGestureListener);
    
                // Set double tap listener.
                activityGestureDetectorCompat.setOnDoubleTapListener(activityGestureListener);
            }
    
            if(imageViewGestureDetectorCompat==null)
            {
                // This gesture listener is used with the image view.
                CommonGestureListener imageViewGestureListener = new CommonGestureListener();
    
                // Set source view object.
                imageViewGestureListener.setSrcView(imageView);
    
                // Create image view gesture detector.
                imageViewGestureDetectorCompat = new GestureDetectorCompat(this, imageViewGestureListener);
    
                // Set double tap listener.
                imageViewGestureDetectorCompat.setOnDoubleTapListener(imageViewGestureListener);
            }
    
            // Set a new OnTouchListener to image view.
            imageView.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    // When image view ontouch event occurred, call it's gesture detector's onTouchEvent method.
                    imageViewGestureDetectorCompat.onTouchEvent(motionEvent);
                    // Return true to tell android OS this listener has consumed the event, do not need to pass the event to other listeners.
                    return true;
                }
            });
        }
    
        @Override
        public boolean onTouchEvent(MotionEvent event) {
            // When this activity's ouTouchEvent occurred. Call activity gesture detector onTouchEvent method.
            this.activityGestureDetectorCompat.onTouchEvent(event);
            return super.onTouchEvent(event);
        }
    }

4. Custom Common Android Gesture Listener Java Class.

  1. CommonGestureListener.java
    package com.dev2qa.gestureexample;
    
    import android.util.Log;
    import android.view.GestureDetector;
    import android.view.MotionEvent;
    import android.view.View;
    import android.widget.ImageView;
    
    
    public class CommonGestureListener extends GestureDetector.SimpleOnGestureListener {
    
        private static String TAG_COMMON_GESTURE_DETECTOR = "COMMON_GESTURE_DETECTOR";
    
        public View srcView = null;
    
        public View getSrcView() {
            return srcView;
        }
    
        public void setSrcView(View srcView) {
            this.srcView = srcView;
        }
    
        @Override
        public boolean onDown(MotionEvent motionEvent) {
    
            Log.d(TAG_COMMON_GESTURE_DETECTOR, buildMessage("onDown()"));
            return true;
        }
    
        @Override
        public void onShowPress(MotionEvent motionEvent) {
    
            Log.d(TAG_COMMON_GESTURE_DETECTOR, buildMessage("onShowPress()"));
        }
    
        @Override
        public boolean onSingleTapUp(MotionEvent motionEvent) {
            Log.d(TAG_COMMON_GESTURE_DETECTOR, buildMessage("onSingleTapUp()"));
            return true;
        }
    
        @Override
        public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
            Log.d(TAG_COMMON_GESTURE_DETECTOR, buildMessage("onScroll()"));
            return true;
        }
    
        @Override
        public void onLongPress(MotionEvent motionEvent) {
            Log.d(TAG_COMMON_GESTURE_DETECTOR, buildMessage("onLongPress()"));
        }
    
        @Override
        public boolean onFling(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
            Log.d(TAG_COMMON_GESTURE_DETECTOR, buildMessage("onFling()"));
            return true;
        }
    
        @Override
        public boolean onSingleTapConfirmed(MotionEvent motionEvent) {
            Log.d(TAG_COMMON_GESTURE_DETECTOR, buildMessage("onSingleTapConfirmed()"));
            return true;
        }
    
        @Override
        public boolean onDoubleTap(MotionEvent motionEvent) {
            Log.d(TAG_COMMON_GESTURE_DETECTOR, buildMessage("onDoubleTap()"));
            return true;
        }
    
        @Override
        public boolean onDoubleTapEvent(MotionEvent motionEvent) {
            Log.d(TAG_COMMON_GESTURE_DETECTOR, buildMessage("onDoubleTapEvent()"));
            return true;
        }
    
        private String buildMessage(String message)
        {
            StringBuffer retBuf = new StringBuffer();
            if(srcView instanceof ImageView)
            {
                retBuf.append("Image view gesture : ");
            }
            retBuf.append(message);
            return retBuf.toString();
        }
    }

5. Main Layout Xml File.

  1. activity_main.xml
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:gravity="center">
    
        <ImageView
            android:id="@+id/common_gesture_imageview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/green_button" />
    
    </LinearLayout>

Leave a Comment

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

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