How To Detect Common Android Gestures

We all know that you can use gestures in 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. You can also make your custom class implements interface android.view.GestureDetector.OnGestureListener or GestureDetector.OnDoubleTapListener or GestureDetector.OnContextClickListener, but SimpleOnGestureListener class has already implements those three interface.
  2. Override the methods in SimpleOnGestureListener which you want to execute when according gestures event happened.
  3. Create an instance of above custom gestures listener class.
  4. Create an instance of android.support.v4.view.GestureDetectorCompat, use the custom gesture listener instance as input parameter.
  5. Invoke GestureDetectorCompat instance’s onTouchEvent method in activity’s onTouchEvent method to make the activity listen and catch user gestures.
  6. 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 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 logcat console.
  4. Add an image view in the main activity class.
  5. In main activity class, create two instance of GestureDetectorCompat class use 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 is the related java, layout and image files in this example.detect common android gestures java files
  8. When execute this example and make different gestures on the image view or activity screen, you can see below log console output.
    detect common android gestures logcat output
READ :   Android ListView Example

3. Main Activity Java File.

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 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.

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;

/**
 * Created by Jerry on 4/18/2018.
 */

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.

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>
(Visited 55 times, 2 visits today)

Leave a Reply

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