Kotlin - How to handle swipe Gesture in Android Application?

Published February 21, 2020

In this post we are going to learn how to hanlde swipe Gesture in Android

Let's Start

Step 1: Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project

Step 2: Updated Activity xml file with below code

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
                xmlns:tools="https://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:padding="4dp"
                android:id="@+id/relativeLayout"
                tools:context=".MainActivity">
    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAlignment="center"
            android:layout_centerInParent="true"
            android:textSize="18sp"
            android:textStyle="bold"
            android:padding="16dp"
            android:lineSpacingExtra="2dp"
            android:textColor="@color/colorPrimary"

            android:text="Swipe Left to right and Right to Left to detect Swipe Gesture"/>
</RelativeLayout>

 

Step 3: Create class and add below code

package com.rrtutors.androidsamples.guestures

import android.content.Context
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.View
import com.rrtutors.androidsamples.guestures.OnSwipeTouchListener.GestureListener



public abstract class OnSwipeTouchListener() :View.OnTouchListener{

    constructor(c: Context) : this() {
        gestureDetector = GestureDetector(c, GestureListener())
    }

    private var gestureDetector: GestureDetector?=null;

    override fun onTouch(v: View?, event: MotionEvent?): Boolean {

        return gestureDetector?.onTouchEvent(event)!!;
    }

    inner class GestureListener: GestureDetector.OnGestureListener{
        private val SWIPE_THRESHOLD = 100
        private val SWIPE_VELOCITY_THRESHOLD = 100
        override fun onShowPress(e: MotionEvent?) {


        }

        override fun onSingleTapUp(e: MotionEvent?): Boolean {
               //onSingleTapUp(e)
            return true;
        }

        override fun onDown(e: MotionEvent?): Boolean {

            return true;
        }

        override fun onFling(e1: MotionEvent?, e2: MotionEvent?, velocityX: Float, velocityY: Float): Boolean {
            try {
                val diffY = e2?.getY()!! - e1?.getY()!!
                val diffX = e2.getX() - e1.getX()
                if (Math.abs(diffX) > Math.abs(diffY)) {
                    if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                        if (diffX > 0) {
                            onSwipeRight()
                        } else {
                            onSwipeLeft()
                        }
                    }
                } else {
                    if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
                        if (diffY > 0) {
                            onSwipeDown()
                        } else {
                            onSwipeUp()
                        }
                    }
                }
            } catch (exception: Exception) {
                exception.printStackTrace()
            }

            return false
        }

        override fun onScroll(e1: MotionEvent?, e2: MotionEvent?, distanceX: Float, distanceY: Float): Boolean {
            return true;
        }

        override fun onLongPress(e: MotionEvent?) {

        }

    }

    abstract fun onSwipeRight();
    abstract fun onSwipeLeft();
    private fun onSwipeUp() {}
    private fun onSwipeDown() {}
    private fun onClick() {}
    private fun onDoubleClick() {}
    private fun onLongClick() {}
}

 

Step 4: Update Activity file with below code

package com.rrtutors.androidsamples.guestures

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.rrtutors.androidsamples.MainActivity
import com.rrtutors.androidsamples.R
import kotlinx.android.synthetic.main.activity_guesture.*

class GuestureActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_guesture)


        relativeLayout.setOnTouchListener(object : OnSwipeTouchListener(this@GuestureActivity){
            override fun onSwipeRight() {

                Toast.makeText(this@GuestureActivity, "Swipe Right gesture detected", Toast.LENGTH_SHORT).show();

            }

            override fun onSwipeLeft() {
                Toast.makeText(this@GuestureActivity, "Swipe Left gesture detected", Toast.LENGTH_SHORT).show();

            }


        })
    }
}

 

Step 5: Let's  run application

Kotlin - Android Swipe gestures

Kotlin - Android Swipe Gesture

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

4462 Views