How to detect swipe direction between left/right and up/down in Android?

AndroidApps/ApplicationsMobile Development

This example demonstrates how do I detect swipe direction between left/right and up/down in android.

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 − Add the following code to res/layout/activity_main.xml.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:id="@+id/relativeLayout"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:padding="16dp"
   tools:context=".MainActivity">
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:text="Swipe to Detect swipe Event"
      android:textSize="24sp"
      android:textStyle="bold" />
</RelativeLayout>

Step 3 − Add the following code to src/MainActivity.java

import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
   OnSwipeTouchListener onSwipeTouchListener;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      onSwipeTouchListener = new OnSwipeTouchListener(this, findViewById(R.id.relativeLayout));
   }
   public static class OnSwipeTouchListener implements View.OnTouchListener {
      private final GestureDetector gestureDetector;
      Context context;
      OnSwipeTouchListener(Context ctx, View mainView) {
         gestureDetector = new GestureDetector(ctx, new GestureListener());
         mainView.setOnTouchListener(this);
         context = ctx;
      }
      @Override
      public boolean onTouch(View v, MotionEvent event) {
         return gestureDetector.onTouchEvent(event);
      }
      public class GestureListener extends
      GestureDetector.SimpleOnGestureListener {
         private static final int SWIPE_THRESHOLD = 100;
         private static final int SWIPE_VELOCITY_THRESHOLD = 100;
         @Override
         public boolean onDown(MotionEvent e) {
            return true;
         }
         @Override
         public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            boolean result = false;
            try {
               float diffY = e2.getY() - e1.getY();
               float 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();
                     }
                     result = true;
                  }
               }
               else if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
                  if (diffY > 0) {
                     onSwipeBottom();
                  } else {
                     onSwipeTop();
                  }
                  result = true;
               }
            }
            catch (Exception exception) {
               exception.printStackTrace();
            }
            return result;
         }
      }
      void onSwipeRight() {
         Toast.makeText(context, "Swiped Right", Toast.LENGTH_SHORT).show();
         this.onSwipe.swipeRight();
      }
      void onSwipeLeft() {
         Toast.makeText(context, "Swiped Left", Toast.LENGTH_SHORT).show();
         this.onSwipe.swipeLeft();
      }
      void onSwipeTop() {
         Toast.makeText(context, "Swiped Up", Toast.LENGTH_SHORT).show();
         this.onSwipe.swipeTop();
      }
      void onSwipeBottom() {
         Toast.makeText(context, "Swiped Down", Toast.LENGTH_SHORT).show();
         this.onSwipe.swipeBottom();
      }
      interface onSwipeListener {
         void swipeRight();
         void swipeTop();
         void swipeBottom();
         void swipeLeft();
      }
      onSwipeListener onSwipe;
   }
}

Step 4 − Add the following code to androidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −

Click here to download the project code.

raja
Published on 22-Nov-2019 12:26:18
Advertisements