Xamarin.Android - Gesture Detector

Introduction

 
The gesture means finger movement in the touchscreen interface. The different types of gestures are Tab, drag, Flick, Swipe, double tab, pinch, Three-finger pinch, three-finger swipe, touch and hold, rotate, shake. In this article, we are going to learn how to implement gestures in our application.
 
Xamarin.Android - Gesture Detector
 
Let's begin.
 
Create a Xamarin android project in Visual Studio 2019. Go to Visual Studio >> Create New Project >> select Android App (Xamarin) and click Next. In the next dialog box, give Project Name, Location Name, Location and click the Create button.
 
Xamarin.Android - Gesture Detector
 
After the project creation, open content_main.xml file and add TextView widget in the screen and set width and height as match_parent. The code is given below:
  1. <?xml version="1.0" encoding="utf-8"?>    
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    
  3.                 xmlns:app="http://schemas.android.com/apk/res-auto"    
  4.                 xmlns:tools="http://schemas.android.com/tools"    
  5.                 android:layout_width="match_parent"    
  6.                 android:layout_height="match_parent"    
  7.                 tools:showIn="@layout/activity_main">    
  8.     
  9.              <TextView    
  10.                 android:id="@+id/imageView"    
  11.                 android:layout_width="match_parent"    
  12.                 android:text="Gesture"    
  13.                 android:textSize="35dp"    
  14.                 android:gravity="center"    
  15.                 android:layout_centerInParent="true"    
  16.                 android:textColor="@android:color/black"    
  17.                 android:layout_height="match_parent"/>    
  18.     
  19. </RelativeLayout>    
Next, open the MainActivity.cs class by double-clicking it. The gesture interfaces are going to implement in this MainActivity. This Interfaces will create the following gesture methods:
  •  OnDown
  • OnScroll
  • OnSingleTabUp
  • OnLongPress
  • OnFling
  • OnShowPress
The Method definitions are here:
  • OnDown(MotionEvent e) – Down MotionEvent will get triggers. One Touch or tab the UI
  • OnFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) - Notifies of swipe occurs in the start and end of MotionEvent or threshold of swipe.
  • OnLongPress(MotionEvent e) - This event will get trigger. Once long touch or tab the UI
  • OnScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) - While scrolling this event will be triggered.
  • OnShowPress(MotionEvent e) - performed a done MotionEvent and not above performed a moment.
  • OnSingleTapUp(MotionEvent e) - On single tab, the widget or layout this event will be triggered.
Based on the Fling start and end velocity, we can set the swipe directions:
  1. Top to Bottom
  2. Bottom to Top
  3. Right to Left
  4. Left to Right.
Velocity has two types:
  1. Swipe Threshold - The difference between the initial and final position of touch in any four directions that we already have seen.
  2. Velocity Threshold - How quickly the gesture is swiped.
Finally, set this interface to the TextView we already designed in content_main.xml. The page code is given below
  1. using System;  
  2. using Android.App;  
  3. using Android.OS;  
  4. using Android.Runtime;  
  5. using Android.Support.Design.Widget;  
  6. using Android.Support.V7.App;  
  7. using Android.Views;  
  8. using Android.Widget;  
  9. using static Android.Views.GestureDetector;  
  10. using static Android.Views.View;  
  11. namespace TVS_Demo {  
  12.     [Activity(Theme = "@style/AppTheme.NoActionBar", MainLauncher = true, ScreenOrientation = Android.Content.PM.ScreenOrientation.Portrait)]  
  13.     public class MainActivity: AppCompatActivity, IOnTouchListener, IOnGestureListener {  
  14.         private TextView txtGestureView;  
  15.         private readonly int SWIPE_MIN_DISTANCE = 120;  
  16.         private static int SWIPE_MAX_OFF_PATH = 250;  
  17.         private static int SWIPE_THRESHOLD_VELOCITY = 200;  
  18.         private int imageIndex = 0;  
  19.         private GestureDetector gestureDetector;  
  20.         protected override void OnCreate(Bundle savedInstanceState) {  
  21.             base.OnCreate(savedInstanceState);  
  22.             Xamarin.Essentials.Platform.Init(this, savedInstanceState);  
  23.             SetContentView(Resource.Layout.activity_main);  
  24.             txtGestureView = FindViewById < TextView > (Resource.Id.imageView);  
  25.             gestureDetector = new GestureDetector(this);  
  26.             txtGestureView.SetOnTouchListener(this);  
  27.         }  
  28.         public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults) {  
  29.             Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);  
  30.             base.OnRequestPermissionsResult(requestCode, permissions, grantResults);  
  31.         }  
  32.         public bool OnTouch(View v, MotionEvent e) {  
  33.             Toast.MakeText(this"On Touch", ToastLength.Short).Show();  
  34.             return gestureDetector.OnTouchEvent(e);  
  35.         }  
  36.         public bool OnDown(MotionEvent e) {  
  37.             Toast.MakeText(this"On Down", ToastLength.Short).Show();  
  38.             return true;  
  39.         }  
  40.         public bool OnFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {  
  41.             bool result = false;  
  42.             try {  
  43.                 float diffY = e2.GetY() - e1.GetY();  
  44.                 float diffX = e2.GetX() - e1.GetX();  
  45.                 if (Math.Abs(diffX) > Math.Abs(diffY)) {  
  46.                     if (Math.Abs(diffX) > SWIPE_THRESHOLD_VELOCITY && Math.Abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {  
  47.                         if (diffX > 0) {  
  48.                             //onSwipeRight();    
  49.                             if (imageIndex > 0) {  
  50.                                 imageIndex--;  
  51.                             }  
  52.                             txtGestureView.Text = "Swiped Right";  
  53.                         } else {  
  54.                             if (imageIndex < 28) {  
  55.                                 imageIndex++;  
  56.                             }  
  57.                             //onSwipeLeft();    
  58.                             txtGestureView.Text = "Swiped Left";  
  59.                         }  
  60.                         result = true;  
  61.                     }  
  62.                 } else  
  63.                 if (Math.Abs(diffY) > SWIPE_THRESHOLD_VELOCITY && Math.Abs(velocityY) > SWIPE_THRESHOLD_VELOCITY) {  
  64.                     if (diffY > 0) {  
  65.                         //onSwipeBottom();    
  66.                         txtGestureView.Text = "Swiped Bottom";  
  67.                     } else {  
  68.                         //onSwipeTop();    
  69.                         txtGestureView.Text = "Swiped Top";  
  70.                     }  
  71.                     result = true;  
  72.                 }  
  73.             } catch (Exception exception) {  
  74.                 Console.WriteLine(exception.Message);  
  75.             }  
  76.             return result;  
  77.         }  
  78.         public void OnLongPress(MotionEvent e) {  
  79.             Toast.MakeText(this"On Long Press", ToastLength.Short).Show();  
  80.         }  
  81.         public bool OnScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {  
  82.             Toast.MakeText(this"On Scroll", ToastLength.Short).Show();  
  83.             return true;  
  84.         }  
  85.         public void OnShowPress(MotionEvent e) {  
  86.             Toast.MakeText(this"On Show Press", ToastLength.Short).Show();  
  87.         }  
  88.         public bool OnSingleTapUp(MotionEvent e) {  
  89.             Toast.MakeText(this"On Single Tab Up", ToastLength.Short).Show();  
  90.             return true;  
  91.         }  
  92.     }  
  93. }  
Run your application and get output, as shown in the below gif.
 
Xamarin.Android - Gesture Detector
 
The full source code is here - GitHub  
 

Conclusion 

 
I hope you all understood the gestures and how to implement them in our applications. Thanks for reading!