How to Detect Swipe Direction in Android? - GeeksforGeeks

05 Aug, 2021
Detecting gestures is a very important feature that many app developers focus on. There can be a number of gestures that could be required to perform certain actions. For example, a user might need to swipe the screen from left to right to unlock the screen. Similarly, vice-versa might be needed. In such cases, it is necessary to detect the direction of the swipe or gesture made by the user. Similarly, most gaming applications depend heavily on user gestures to perform desired actions. So through this article, we will show you how you could detect the swipe direction of the user input on the screen.
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.
Step 2: Add this in the Main code (MainActivity.kt)
Refer to the comments inside the code for better understanding.
Kotlin
import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.view.GestureDetectorimport android.view.MotionEventimport android.widget.Toastimport kotlin.math.abs  class MainActivity : AppCompatActivity(), GestureDetector.OnGestureListener {        // Declaring gesture detector, swipe threshold, and swipe velocity threshold    private lateinit var gestureDetector: GestureDetector    private val swipeThreshold = 100    private val swipeVelocityThreshold = 100      override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        setContentView(R.layout.activity_main)                  // Initializing the gesture detector        gestureDetector = GestureDetector(this)    }      // Override this method to recognize touch event    override fun onTouchEvent(event: MotionEvent): Boolean {        return if (gestureDetector.onTouchEvent(event)) {            true        }        else {            super.onTouchEvent(event)        }    }      // All the below methods are GestureDetector.OnGestureListener members    // Except onFling, all must "return false" if Boolean return type    // and "return" if no return type    override fun onDown(e: MotionEvent?): Boolean {        return false    }      override fun onShowPress(e: MotionEvent?) {        return    }      override fun onSingleTapUp(e: MotionEvent?): Boolean {        return false    }      override fun onScroll(e1: MotionEvent?, e2: MotionEvent?, distanceX: Float, distanceY: Float): Boolean {        return false    }      override fun onLongPress(e: MotionEvent?) {        return    }      override fun onFling(e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float): Boolean {        try {            val diffY = e2.y - e1.y            val diffX = e2.x - e1.x            if (abs(diffX) > abs(diffY)) {                if (abs(diffX) > swipeThreshold && abs(velocityX) > swipeVelocityThreshold) {                    if (diffX > 0) {                        Toast.makeText(applicationContext, "Left to Right swipe gesture", Toast.LENGTH_SHORT).show()                    }                    else {                        Toast.makeText(applicationContext, "Right to Left swipe gesture", Toast.LENGTH_SHORT).show()                    }                }            }        }        catch (exception: Exception) {            exception.printStackTrace()        }        return true    }}
No layout code is needed (activity_main.xml)
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout     xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity"></androidx.constraintlayout.widget.ConstraintLayout>
Output:
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Retrofit with Kotlin Coroutine in Android
Android Listview in Java with Example
How to Read Data from SQLite Database in Android?
Flutter - Custom Bottom Navigation Bar
How to Change the Background Color After Clicking the Button in Android?
Android UI Layouts
Kotlin Array
Retrofit with Kotlin Coroutine in Android
Kotlin Setters and Getters
MVP (Model View Presenter) Architecture Pattern in Android with Example