Android Gesture Recognition Applications: Hand-on instructions for learning GestureDetector

Keywords: Android xml encoding Java

Preface

  • Gesture recognition is very common in Android development applications
  • Today, carson will explain in detail the Android Gesture Recognition class: the use of the GestureDetector class.(with examples)

Catalog

brief introduction

Next, I'll take an ex amp le and describe in detail the use interface of GestureDetector, the use class.

Interface 1:OnGestureListener

1. Role

Detect user's actions on screen: press instantly, press, long press, tap, fast slide, drag

2. Steps to use

// Step 1: Create a Gesture Detector Instance & Pass in the OnGestureListener interface (requiring replication of the corresponding method)
// There are three constructors, and the second one is commonly used
// 1. GestureDetector gestureDetector=new GestureDetector(GestureDetector.OnGestureListener listener);
// 2. GestureDetector gestureDetector=new GestureDetector(Context context,GestureDetector.OnGestureListener listener);
// 3. GestureDetector gestureDetector=new GestureDetector(Context context,GestureDetector.SimpleOnGestureListener listener);
    GestureDetector mGestureDetector = new GestureDetector(this, new GestureDetector.OnGestureListener() {

        // 1. Touch screen by user
        public boolean onDown(MotionEvent e) {
            Log.i("MyGesture", "onDown");
            return false;
        }

        // 2. The user touches the touch screen without releasing or dragging it
        // Difference from onDown(): No release/drag
        // That is, onDown () executes when the user clicks and onShowPress executes when no release/drag occurs at the moment of press
        public void onShowPress(MotionEvent e) {
            Log.i("MyGesture", "onShowPress");
        }

        // 3. User Long Press Touch Screen
        public void onLongPress(MotionEvent e) {
            Log.i("MyGesture", "onLongPress");
        }

        // 4. The user taps the screen and raises it
        public boolean onSingleTapUp(MotionEvent e) {
            Log.i("MyGesture", "onSingleTapUp");
            return true;
        }

        // 5. User Press Touch Screen & Drag
        public boolean onScroll(MotionEvent e1, MotionEvent e2,
                                float distanceX, float distanceY) {
            Log.i("MyGesture", "onScroll:");
            return true;
        }

        // 6. Release the touch screen when the user presses it and moves it quickly
        // Parameters:
        // e1: First ACTION_DOWN MotionEvent
        // e2: Last ACTION_MOVE MotionEvent
        // Moving speed on velocityX:X axis, pixels/second
        // Velocity Y:Y axis movement speed, pixels/second
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                               float velocityY) {
            Log.i("MyGesture", "onFling");
            return true;
        }

    });

// Step 2-1: Let a View detect gestures - override the onTouch function of the View, and hand the View's touch events to GestureDetector to respond to user gestures
    View.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            mGestureDetector.onTouchEvent(event);
            return true; // Note: Return to true to receive touch events completely
        }
    });

// Step 2-2: Let an Activity detect gestures: Rewrite the dispatchTouchEvent function of the Activity, and hand the touch event to GestureDetector to respond to user gestures
  @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        mGestureDetector.onTouchEvent(ev); // Let GestureDetector respond to touch events
        super.dispatchTouchEvent(ev); // Let Activity respond to touch events
        return false;
    }

3. Example description

Now do gesture detection on a TextView
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    >

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="600dp"
        android:text="carson_ho Test"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {

    TextView mTextView;
    GestureDetector mGestureDetector;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Step 1: Create a Gesture Detector Instance & Pass in the OnGestureListener interface (requiring replication of the corresponding method)
        mGestureDetector = new GestureDetector(this, new GestureDetector.OnGestureListener() {

            // 1. Touch screen by user
            public boolean onDown(MotionEvent e) {
                Log.i("MyGesture", "onDown");
                return false;
            }

            // 2. The user touches the touch screen without releasing or dragging it
            // Difference from onDown(): No release/drag
            // That is, onDown () executes when the user clicks and onShowPress executes when no release/drag occurs at the moment of press
            public void onShowPress(MotionEvent e) {
                Log.i("MyGesture", "onShowPress");
            }

            // 3. User Long Press Touch Screen
            public void onLongPress(MotionEvent e) {
                Log.i("MyGesture", "onLongPress");
            }

            // 4. The user taps the screen and raises it
            public boolean onSingleTapUp(MotionEvent e) {
                Log.i("MyGesture", "onSingleTapUp");
                return true;
            }

            // 5. User Press Touch Screen & Drag
            public boolean onScroll(MotionEvent e1, MotionEvent e2,
                                    float distanceX, float distanceY) {
                Log.i("MyGesture", "onScroll:");
                return true;
            }

            // 6. Release the touch screen when the user presses it and moves it quickly
            // Parameters:
            // e1: First ACTION_DOWN MotionEvent
            // e2: Last ACTION_MOVE MotionEvent
            // Moving speed on velocityX:X axis, pixels/second
            // Velocity Y:Y axis movement speed, pixels/second
            public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                                   float velocityY) {
                Log.i("MyGesture", "onFling");
                return true;
            }

        });

        // Step 2: Let TextView detect gestures: Rewrite the onTouch function of View and hand the touch event to GestureDetector to respond to user gestures
        mTextView = (TextView) findViewById(R.id.textView);
        mTextView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                mGestureDetector.onTouchEvent(event);
                return false;
            }
        });
    }
}

4. Diagram

I make a series of gestures on the screen for testing

Interface 2: OnDoubleTapListener

1. Role

Detect user click, double click screen

2. Steps to use

// Step 1: Create an instance of a gesture detector
    // Note: When using the OnDoubleTapListener interface, GestureDetector is required, whereas the creation of GestureDetector must pass into the OnGestureListener interface
    // So when using the OnDoubleTapListener interface, you must also implement the OnGestureListener interface
    // There are three constructors, and the second one is commonly used
    // 1. GestureDetector gestureDetector=new GestureDetector(GestureDetector.OnGestureListener listener);
    // 2. GestureDetector gestureDetector=new GestureDetector(Context context,GestureDetector.OnGestureListener listener);
    // 3. GestureDetector gestureDetector=new GestureDetector(Context context,GestureDetector.SimpleOnGestureListener listener);
        GestureDetector mGestureDetector = new GestureDetector(this, new GestureDetector.OnGestureListener() {

            // 1. Touch screen by user
            public boolean onDown(MotionEvent e) {
                Log.i("MyGesture", "onDown");
                return false;
            }

            // 2. The user touches the touch screen without releasing or dragging it
            // Difference from onDown(): No release/drag
            // That is, onDown () executes when the user clicks and onShowPress executes when no release/drag occurs at the moment of press
            public void onShowPress(MotionEvent e) {
                Log.i("MyGesture", "onShowPress");
            }

            // 3. User Long Press Touch Screen
            public void onLongPress(MotionEvent e) {
                Log.i("MyGesture", "onLongPress");
            }

            // 4. The user taps the screen and raises it
            public boolean onSingleTapUp(MotionEvent e) {
                Log.i("MyGesture", "onSingleTapUp");
                return true;
            }

            // 5. User Press Touch Screen & Drag
            public boolean onScroll(MotionEvent e1, MotionEvent e2,
                                    float distanceX, float distanceY) {
                Log.i("MyGesture", "onScroll:");
                return true;
            }

            // 6. Release the touch screen when the user presses it and moves it quickly
            // Parameters:
            // e1: First ACTION_DOWN MotionEvent
            // e2: Last ACTION_MOVE MotionEvent
            // Moving speed on velocityX:X axis, pixels/second
            // Velocity Y:Y axis movement speed, pixels/second
            public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                                   float velocityY) {
                Log.i("MyGesture", "onFling");
                return true;
            }

        });

// Step 2: Create and set the OnDoubleTapListener interface implementation class
    mGestureDetector.setOnDoubleTapListener(new GestureDetector.OnDoubleTapListener() {

        // 1. Click Events
        // about OnDoubleTapListener.onSingleTapConfirmed() andOnGestureListener.onSingleTapUpDifferences between ()
        // onSingleTapConfirmed: Click again (that is, double-click) and it will not execute
        // onSingleTapUp: Hand lift will execute
        public boolean onSingleTapConfirmed(MotionEvent e) {
            Log.i("MyGesture", "onSingleTapConfirmed");
            return false;
        }

        // 2. Double-click Events
        public boolean onDoubleTap(MotionEvent e) {
            Log.i("MyGesture", "onDoubleTap");
            return false;
        }
        // 3. Actions occurring in the double-click interval
        // Other actions that occur between double-clicks after onDoubleTap is triggered, including down, up, and move events;
        public boolean onDoubleTapEvent(MotionEvent e) {
            Log.i("MyGesture", "onDoubleTapEvent");
            return false;
        }
    });

// Step 3-1: Ask a View to detect gestures - override the onTouch function of the View, and hand the View's touch events to GestureDetector to respond to user gestures
    View.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            mGestureDetector.onTouchEvent(event);
            return true; // Note: Return to true to receive touch events completely
        }
    });

// Step 3-2: Let an Activity detect gestures: Rewrite the dispatchTouchEvent function of the Activity, and hand the touch event to GestureDetector to respond to user gestures
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        mGestureDetector.onTouchEvent(ev); // Let GestureDetector respond to touch events
        super.dispatchTouchEvent(ev); // Let Activity respond to touch events
        return false;
    }

3. Example description

Now do gesture detection on a TextView
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    >

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="600dp"
        android:text="carson_ho Test"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {

    TextView mTextView;
    GestureDetector mGestureDetector;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Step 1: Create a Gesture Detector Instance & Pass in the OnGestureListener interface (requiring replication of the corresponding method)
        mGestureDetector = new GestureDetector(this, new GestureDetector.OnGestureListener() {

            // 1. Touch screen by user
            public boolean onDown(MotionEvent e) {
                Log.i("MyGesture1", "onDown");
                return false;
            }

            // 2. The user touches the touch screen without releasing or dragging it
            // Difference from onDown(): No release/drag
            // That is, onDown () executes when the user clicks and onShowPress executes when no release/drag occurs at the moment of press
            public void onShowPress(MotionEvent e) {
                Log.i("MyGesture", "onShowPress");
            }

            // 3. User Long Press Touch Screen
            public void onLongPress(MotionEvent e) {
                Log.i("MyGesture", "onLongPress");
            }

            // 4. The user taps the screen and raises it
            public boolean onSingleTapUp(MotionEvent e) {
                Log.i("MyGesture", "onSingleTapUp");
                return true;
            }

            // 5. User Press Touch Screen & Drag
            public boolean onScroll(MotionEvent e1, MotionEvent e2,
                                    float distanceX, float distanceY) {
                Log.i("MyGesture", "onScroll:");
                return true;
            }

            // 6. Release the touch screen when the user presses it and moves it quickly
            // Parameters:
            // e1: First ACTION_DOWN MotionEvent
            // e2: Last ACTION_MOVE MotionEvent
            // Moving speed on velocityX:X axis, pixels/second
            // Velocity Y:Y axis movement speed, pixels/second
            public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                                   float velocityY) {
                Log.i("MyGesture", "onFling");
                return true;
            }

        });

        // Step 2: Create and set the OnDoubleTapListener interface implementation class
        mGestureDetector.setOnDoubleTapListener(new GestureDetector.OnDoubleTapListener() {

            // 1. Click Events
            // about OnDoubleTapListener.onSingleTapConfirmed() andOnGestureListener.onSingleTapUpDifferences between ()
            // onSingleTapConfirmed: Click again (that is, double-click) and it will not execute
            // onSingleTapUp: Hand lift will execute
            public boolean onSingleTapConfirmed(MotionEvent e) {
                Log.i("MyGesture", "onSingleTapConfirmed");
                return false;
            }

            // 2. Double-click Events
            public boolean onDoubleTap(MotionEvent e) {
                Log.i("MyGesture", "onDoubleTap");
                return false;
            }
            // 3. Actions occurring in the double-click interval
            // Other actions that occur between double-clicks after onDoubleTap is triggered, including down, up, and move events;
            public boolean onDoubleTapEvent(MotionEvent e) {
                Log.i("MyGesture", "onDoubleTapEvent");
                return false;
            }
        });

        // Step 3: Rewrite the onTouch function of View and hand the touch event to GestureDetector to respond to user gestures
        mTextView = (TextView) findViewById(R.id.textView);

        mTextView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                mGestureDetector.onTouchEvent(event);
                return true;
            }
        });
    }
}

4. Test results

The log effect is as follows

Use class: SimpleOnGestureListener

1. Role

Gesture detection functions integrated with two interfaces

2. Differences from the above two interfaces

  • Functions in the OnGestureListener and OnDoubleTapListener interfaces are mandatory and must be overridden
  • Functions of the SimpleOnGestureListener class can optionally be overridden as needed, because the SimpleOnGestureListener class itself already implements all the functions of the two interfaces, but it is empty inside.

3. Steps to use

// Step 1: Create an instance of a gesture detector
    // There are three constructors, the third one used here
    // 1. GestureDetector gestureDetector=new GestureDetector(GestureDetector.OnGestureListener listener);
    // 2. GestureDetector gestureDetector=new GestureDetector(Context context,GestureDetector.OnGestureListener listener);
    // 3. GestureDetector gestureDetector=new GestureDetector(Context context,GestureDetector.SimpleOnGestureListener listener);
    GestureDetector mGestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {

        // Functions of the OnGestureListener interface
        // 1. Touch screen by user
        public boolean onDown(MotionEvent e) {
            Log.i("MyGesture1", "onDown");
            return false;
        }

        // 2. The user touches the touch screen without releasing or dragging it
        // Difference from onDown(): No release/drag
        // That is, onDown () executes when the user clicks and onShowPress executes when no release/drag occurs at the moment of press
        public void onShowPress(MotionEvent e) {
            Log.i("MyGesture", "onShowPress");
        }

        // 3. User Long Press Touch Screen
        public void onLongPress(MotionEvent e) {
            Log.i("MyGesture", "onLongPress");
        }

        // 4. The user taps the screen and raises it
        public boolean onSingleTapUp(MotionEvent e) {
            Log.i("MyGesture", "onSingleTapUp");
            return true;
        }

        // 5. User Press Touch Screen & Drag
        public boolean onScroll(MotionEvent e1, MotionEvent e2,
                                float distanceX, float distanceY) {
            Log.i("MyGesture", "onScroll:");
            return true;
        }

        // 6. Release the touch screen when the user presses it and moves it quickly
        // Parameters:
        // e1: First ACTION_DOWN MotionEvent
        // e2: Last ACTION_MOVE MotionEvent
        // Moving speed on velocityX:X axis, pixels/second
        // Velocity Y:Y axis movement speed, pixels/second
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                               float velocityY) {
            Log.i("MyGesture", "onFling");
            return true;
        }

        // Functions of OnDoubleTapListener
        // 1. Click Events
        // about OnDoubleTapListener.onSingleTapConfirmed() andOnGestureListener.onSingleTapUpDifferences between ()
        // onSingleTapConfirmed: Click again (that is, double-click) and it will not execute
        // onSingleTapUp: Hand lift will execute
        public boolean onSingleTapConfirmed(MotionEvent e) {
            Log.i("MyGesture", "onSingleTapConfirmed");
            return false;
        }

        // 2. Double-click Events
        public boolean onDoubleTap(MotionEvent e) {
            Log.i("MyGesture", "onDoubleTap");
            return false;
        }
        // 3. Actions occurring in the double-click interval
        // Other actions that occur between double-clicks after onDoubleTap is triggered, including down, up, and move events;
        public boolean onDoubleTapEvent(MotionEvent e) {
            Log.i("MyGesture", "onDoubleTapEvent");
            return false;
        }
    });

// Step 2-1: Let a View detect gestures - override the onTouch function of the View, and hand the View's touch events to GestureDetector to respond to user gestures
    View.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            mGestureDetector.onTouchEvent(event);
            return true; // Note: Return to true to receive touch events completely
        }
    });

// Step 2-2: Let an Activity detect gestures: Rewrite the dispatchTouchEvent function of the Activity, and hand the touch event to GestureDetector to respond to user gestures
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        mGestureDetector.onTouchEvent(ev); // Let GestureDetector respond to touch events
        super.dispatchTouchEvent(ev); // Let Activity respond to touch events
        return false;
    }

4. Example description

Now do gesture detection on a TextView
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    >

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="600dp"
        android:text="carson_ho Test"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {

    TextView mTextView;
    GestureDetector mGestureDetector;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Step 1: Create a Gesture Detector Instance & Pass in the OnGestureListener interface (requiring replication of the corresponding method)
        mGestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {

            // Functions of the OnGestureListener interface
            // 1. Touch screen by user
            public boolean onDown(MotionEvent e) {
                Log.i("MyGesture1", "onDown");
                return false;
            }

            // 2. The user touches the touch screen without releasing or dragging it
            // Difference from onDown(): No release/drag
            // That is, onDown () executes when the user clicks and onShowPress executes when no release/drag occurs at the moment of press
            public void onShowPress(MotionEvent e) {
                Log.i("MyGesture", "onShowPress");
            }

            // 3. User Long Press Touch Screen
            public void onLongPress(MotionEvent e) {
                Log.i("MyGesture", "onLongPress");
            }

            // 4. The user taps the screen and raises it
            public boolean onSingleTapUp(MotionEvent e) {
                Log.i("MyGesture", "onSingleTapUp");
                return true;
            }

            // 5. User Press Touch Screen & Drag
            public boolean onScroll(MotionEvent e1, MotionEvent e2,
                                    float distanceX, float distanceY) {
                Log.i("MyGesture", "onScroll:");
                return true;
            }

            // 6. Release the touch screen when the user presses it and moves it quickly
            // Parameters:
            // e1: First ACTION_DOWN MotionEvent
            // e2: Last ACTION_MOVE MotionEvent
            // Moving speed on velocityX:X axis, pixels/second
            // Velocity Y:Y axis movement speed, pixels/second
            public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                                   float velocityY) {
                Log.i("MyGesture", "onFling");
                return true;
            }

            // Functions of OnDoubleTapListener
            // 1. Click Events
            // about OnDoubleTapListener.onSingleTapConfirmed() andOnGestureListener.onSingleTapUpDifferences between ()
            // onSingleTapConfirmed: Click again (that is, double-click) and it will not execute
            // onSingleTapUp: Hand lift will execute
            public boolean onSingleTapConfirmed(MotionEvent e) {
                Log.i("MyGesture", "onSingleTapConfirmed");
                return false;
            }

            // 2. Double-click Events
            public boolean onDoubleTap(MotionEvent e) {
                Log.i("MyGesture", "onDoubleTap");
                return false;
            }
            // 3. Actions occurring in the double-click interval
            // Other actions that occur between double-clicks after onDoubleTap is triggered, including down, up, and move events;
            public boolean onDoubleTapEvent(MotionEvent e) {
                Log.i("MyGesture", "onDoubleTapEvent");
                return false;
            }
        });

        // Step 2: Rewrite the onTouch function of View and hand the touch event to GestureDetector to respond to user gestures
        mTextView = (TextView) findViewById(R.id.textView);
        mTextView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                mGestureDetector.onTouchEvent(event);
                return true;
            }
        });
    }
}

5. Test results

The log effect is as follows

At this point, the use of the GestureDetector class for Android gesture recognition has been explained.

summary

  • This article gives a full explanation of the use of the Android Gesture Detector class.
  • Next, I will continue to introduce the related knowledge in Android development. Interested students can continue to follow my blog Carson_Ho Development Notes

Please help / comment on it!Because your encouragement is my greatest motivation to write!

Posted by Rayn on Sun, 07 Jun 2020 17:46:53 -0700