Android Gestures with Examples
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
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
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>
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
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)
}
}
}
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
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
}
}
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
}
Similar Reads
Android Sensors with Example
In our childhood, we all have played many android games like Moto Racing and Temple run in which by tilting the phone the position of the character changes. So, all these happen because of the sensors present in your Android device. Most Android-powered devices have built-in sensors that measure mot
4 min read
Services in Android with Example
Services in Android are a special component that facilitates an application to run in the background in order to perform long-running operation tasks. The prime aim of a service is to ensure that the application remains active in the background so that the user can operate multiple applications at t
10 min read
OpenIntents in Android with Example
OI refers to the "OpenIntents" project in Android are a way for one app to request an action from another app. This can be done using either explicit or implicit intents, allowing them to share functionality. The OpenIntents project provides a set of commonly-used intents that can be used by develop
4 min read
TextView in Android with Example
TextView is a simple widget that is seen in every android application. This widget is used to display simple text within the android application. We can add custom styling to the text that we have to show. In this article, we will take a look at How to create a simple Text View in an android applica
2 min read
Exceptions in Android with Example
Exceptions in Android refer to abnormal events or conditions that occur during the execution of an app, which can cause the app to crash or behave unexpectedly. There are several types of exceptions that can occur in Android, including: Checked Exceptions: These are exceptions that are checked by th
3 min read
Intent Service in Android with Example
An IntentService is a subclass of Service in Android that is used to handle asynchronous requests (expressed as "Intents") on demand. It runs in the background and stops itself once it has processed all the intents that were sent to it. An IntentService in Java and Kotlin: Kotlin class MyIntentServi
5 min read
Internal Storage in Android with Example
The aim of this article is to show users how to use internal storage. In this article will be creating an application that can write data to a file and store it in internal storage and read data from the file and display it on the main activity using TextView. Saving and loading data on the internal
5 min read
PhotoView in Android with Example
In this article, PhotoView is added to android. PhotoView aims to help produce an easily usable implementation of a zooming Android ImageView using multi-touch and double-tap. Besides that, it has many more features like it notifying the application when the user taps on the photo or when the displa
2 min read
Android ListView in Java with Example
A ListView in Android is a type of AdapterView that displays a vertically scrollable list of items, with each item positioned one below the other. Using an adapter, items are inserted into the list from an array or database efficiently. For displaying the items in the list method setAdaptor() is use
3 min read
Session Management in Android with Example
Session Management is one of the most important features that are to be used in the Android App when you are integrating the login feature in Android. In your android app if you are using a feature of Login then you should have to save the state if the user has signed the first time. Then when the u
6 min read