Skip to content
Related Articles

Related Articles

Android Gestures with Examples
  • Difficulty Level : Hard
  • Last Updated : 23 Feb, 2021

Android supports a range of touch gestures such as tap, double-tap, pinch, swipe, scroll, long press, drag, and fling. Drag and fling may seem similar but drag is the type of scrolling that occurs when a user drags their finger across the touchscreen, while a fling gesture occurs when the user drags and then lifts their finger quickly. A MotionEvent describes the state of touch event via an action code. A long list of action codes is supported by Android: 

  • ACTION_DOWN: A touch event has started.
  • ACTION_MOVE: A change that has occurred during the touch event (between ACTION_DOWN and ACTION_UP).
  • ACTION_UP: The touch event has finished. This contains the final release location.
  • ACTION_CANCEL: The gesture was canceled.

Note: You should perform same action during ACTION_CANCEL and ACTION_UP event.

Important Methods

  • getAction(): extract the action the user performed from the event parameter.

Important Interfaces

  • GestureDetector.OnGestureListener : notifies users when a particular touch event has occurred.
  • GestureDetector.OnDoubleTapListener : notifies users when a double-tap event has occurred.

Example 1

Let us see the way to perform some simple actions on events like ACTION_DOWN, ACTION_UP, etc.

Step 1: Create a New Project

To create a new project in Android Studio, refer to How to Create/Start a New Project in Android Studio. Select Kotlin as the programming language.



Step 2: Working with the activity_main.xml file

Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.

XML

filter_none

edit
close

play_arrow

link
brightness_4
code

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
  
    <TextView
        android:id="@+id/gesture"
        android:layout_width="398dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:hint="Gestures"
        android:textAlignment="center"
        android:textColor="@android:color/black"
        android:textSize="50sp"></TextView>
  
</FrameLayout>

chevron_right


Step 3: Working with the MainActivity.kt file

Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.

Kotlin

filter_none

edit
close

play_arrow

link
brightness_4
code

import android.os.Bundle
import android.util.Log
import android.view.MotionEvent
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
  
// logs are added for better understanding. 
private const val TAG = "Gestures"
  
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
  
    override fun onTouchEvent(event: MotionEvent): Boolean {
  
        return when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                // when we touch or tap on the screen
                Log.d(TAG, "Action was DOWN")
                gesture.text = "Action was DOWN"
                true
            }
            MotionEvent.ACTION_MOVE -> {
                // while pressing on the screen, 
                // we move our finger
                Log.d(TAG, "Action was MOVE")
                gesture.text = "Action was MOVE"
  
                true
            }
            MotionEvent.ACTION_UP -> {
                // Lifting up the finger after
                // pressing on the screen
                Log.d(TAG, "Action was UP")
                gesture.text = "Action was UP"
  
                true
            }
            MotionEvent.ACTION_CANCEL -> {
                Log.d(TAG, "Action was CANCEL")
                gesture.text = "Action was CANCEL"
  
                true
            }
            MotionEvent.ACTION_OUTSIDE -> {
                Log.d(TAG, "Movement occurred outside of screen element")
                gesture.text = "Movement occurred screen element"
  
                true
            }
            else -> super.onTouchEvent(event)
        }
    }
}

chevron_right


Note: You may get an error on the following line:

import kotlinx.android.synthetic.main.activity_main.*



Please refer to this to fix this error.

Output:  

Explanation of Output: 

  • When we click on the screen or press on the screen, you can see in the video it says Action was DOWN 
  • When we move the mouse or the finger while pressing it, TextView says Action was Move.
  • When I release the mouse or lift my finger, it says Action was UP

Example 2 

Now let us see the way to perform some actions on events like single tap, double-tap, long press, etc. The below code uses the same activity_main.xml as used above.  

Working with the MainActivity.kt file: 

Kotlin

filter_none

edit
close

play_arrow

link
brightness_4
code

import android.os.Bundle
import android.util.Log
import android.view.GestureDetector
import android.view.MotionEvent
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.GestureDetectorCompat
import kotlinx.android.synthetic.main.activity_main.*
  
// logs are added for better understanding. 
private const val TAG = "Gestures"
  
// We have to implement the members as well
// because we are implementing the interfaces.
class MainActivity : AppCompatActivity(), GestureDetector.OnGestureListener, 
                                       GestureDetector.OnDoubleTapListener {
  
    private lateinit var detectorCompat: GestureDetectorCompat
  
    public override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
          
        // Instantiate the gesture detector with the
        // application context and an implementation of
        // GestureDetector.OnGestureListener
        // since we have implemented these 
        // interfaces we can simply us the
        // this keyword to refer to the current activity
        detectorCompat = GestureDetectorCompat(this, this)
    }
  
    // this function connects touch events to gestures
    override fun onTouchEvent(event: MotionEvent): Boolean {
        return if (detectorCompat.onTouchEvent(event)) {
            true
        } else {
            super.onTouchEvent(event)
        }
    }
  
    override fun onDown(event: MotionEvent): Boolean {
        Log.d(TAG, "onDown: $event")
        return true
    }
  
    override fun onFling(
            event1: MotionEvent,
            event2: MotionEvent,
            velocityX: Float,
            velocityY: Float
    ): Boolean {
        Log.d(TAG, "onFling: $event1 $event2")
        return true
    }
  
    override fun onLongPress(event: MotionEvent) {
        Log.d(TAG, "onLongPress: $event")
        gesture.text = "Long Press"
    }
  
    override fun onScroll(
            event1: MotionEvent,
            event2: MotionEvent,
            distanceX: Float,
            distanceY: Float
    ): Boolean {
        Log.d(TAG, "onScroll: $event1 $event2")
        return true
    }
  
    override fun onShowPress(event: MotionEvent) {
        Log.d(TAG, "onShowPress: $event")
        gesture.text = "Press"
    }
  
    override fun onSingleTapUp(event: MotionEvent): Boolean {
        Log.d(TAG, "onSingleTapUp: $event")
        gesture.text = "Single Tap"
  
        return true
    }
  
    override fun onDoubleTap(event: MotionEvent): Boolean {
        Log.d(TAG, "onDoubleTap: $event")
        gesture.text = "DoubleTap"
  
        return true
    }
  
    override fun onDoubleTapEvent(event: MotionEvent): Boolean {
        Log.d(TAG, "onDoubleTapEvent: $event")
          
          // simple toast
        Toast.makeText(this, "Double Tap", Toast.LENGTH_SHORT).show() 
        return true
    }
  
    override fun onSingleTapConfirmed(event: MotionEvent): Boolean {
        Log.d(TAG, "onSingleTapConfirmed: $event")
        gesture.text = "Single Tap Confirmed"
  
        return true
    }
}

chevron_right


Output: 

Explanation of Output:  

  • When we single tap on the screen it says single tap and then single tap confirmed because the event was not canceled
  • When we press on the screen it says to press and if I keep pressing for longer it says the long press.
  • When we double-tap double-tap is shown in Text View as well as Toast.

Note: onTouchEvent() is for the activity but you can attach a View.OnTouchListener object to any View object using the setOnTouchListener() method.

By this method, you can perform actions when events are triggered inside a view because OnTouchListener is attached to that particular view. For example, for an ImageView with id “imp”. 

img.setOnTouchListener { view, motionEvent ->

           // … Respond to touch events

           true

}    

// for general view   

findViewById<View>(R.id.my_view).setOnTouchListener { v, event ->

            // … Respond to touch events

           true

 }

My Personal Notes arrow_drop_up
Recommended Articles
Page :