Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to Detect Swipe Direction in Android?

  • Last Updated : 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 by Step Implementation

Step 1: Create a New Project in Android Studio

Want a more fast-paced & competitive environment to learn the fundamentals of Android?
Click here to head to a guide uniquely curated by our experts with the aim to make you industry ready in no time!

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.AppCompatActivity
import android.os.Bundle
import android.view.GestureDetector
import android.view.MotionEvent
import android.widget.Toast
import 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:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
</androidx.constraintlayout.widget.ConstraintLayout>

Output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!