Hello,
You need to rewrite the TouchListener of WebView so that WebView can respond to left and right swipe gestures. Please refer to the following code.
Step 1. Create custom TouchListener and native GestureDetector in Platform/Android
folder.
namespace MauiApp15.Platforms.Droid
{
public class OnSwipeTouchListener : Java.Lang.Object, IOnTouchListener
{
private GestureDetector gestureDetector;
private Android.Webkit.WebView webView;
public OnSwipeTouchListener(Android.Webkit.WebView webView)
{
this.webView = webView;
gestureDetector = new GestureDetector(Platform.CurrentActivity,new GestureListener(webView));
}
public bool OnTouch(global::Android.Views.View? v, MotionEvent? e)
{
return gestureDetector.OnTouchEvent(e);
}
}
public class GestureListener :Java.Lang.Object, GestureDetector.IOnGestureListener
{
private Android.Webkit.WebView webView;
public GestureListener(Android.Webkit.WebView webView)
{
this.webView = webView;
}
public bool OnDown(MotionEvent e)
{
return false;
}
public void OnLongPress(MotionEvent e)
{
}
public bool OnScroll(MotionEvent? e1, MotionEvent e2, float distanceX, float distanceY)
{
return false ;
}
public void OnShowPress(MotionEvent e)
{
}
public bool OnSingleTapUp(MotionEvent e)
{
return false;
}
public bool OnFling(MotionEvent? e1, MotionEvent e2, float velocityX, float velocityY)
{
float x = e2.GetX() - e1.GetX();
float y = e2.GetY() - e1.GetY();
judgeSwiperDirection(x, y);
return true;
}
private void judgeSwiperDirection(float xAxis, float yAxis)
{
bool isYInControlled = Math.Abs(yAxis) <= 100;
if (isYInControlled)
{
if (xAxis > 25)
{
if (null != webView && webView.CanGoForward())
{
webView.GoForward();
}
}
else if (xAxis < -25)
{
if (null != webView && webView.CanGoBack())
{
webView.GoBack();
}
}
}
}
}
}
Step 2. Set up bindings for the WebView in your Maui page.
protected override void OnHandlerChanged()
{
base.OnHandlerChanged();
#if ANDROID
var w = webview.Handler.PlatformView as Android.Webkit.WebView;
if (w != null)
{
OnSwipeTouchListener onSwipeTouchListener = new OnSwipeTouchListener(w);
w.SetOnTouchListener(onSwipeTouchListener);
}
#endif
}
Best Regards,
Alec Liu.
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.