[Android] Enabling scrolling for a WebView inside a ScrollView

RicardoMommRicardoMomm BRMember
edited October 2015 in Xamarin.Forms

I had this problem a while ago and I didn't found a complete solution for this here in the forum so I'm posting a solution using a Custom Renderer that is very simple and worked very well for me and I bet that it should work for other components too. (Eg: ListView inside ScrollView, nested ScrollViews).

I hope others find it useful too.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using Droid.CustomRenderers;

[assembly: ExportRenderer(typeof(WebView), typeof(ScrollableWebViewRendererAndroid))]
namespace Droid.CustomRenderers
{

    public class ScrollableWebViewRendererAndroid : WebViewRenderer
    {

        public ScrollableWebViewRendererAndroid()
        {
            System.Diagnostics.Debug.WriteLine("ScrollableWebViewRendererAndroid()");
        }

        protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
        {
            base.OnElementChanged(e);

            if (e.OldElement != null)
            {
                Control.Touch -= Control_Touch;
            }

            if (e.NewElement != null)
            {
                Control.Touch += Control_Touch;
            }
        }

        void Control_Touch(object sender, Android.Views.View.TouchEventArgs e)
        {
            // Executing this will prevent the Scrolling to be intercepted by parent views
            switch (e.Event.Action)
            {
                case MotionEventActions.Down:
                    Control.Parent.RequestDisallowInterceptTouchEvent(true);
                    break;
                case MotionEventActions.Up:
                    Control.Parent.RequestDisallowInterceptTouchEvent(false);
                    break;
            }
            // Calling this will allow the scrolling event to be executed in the WebView
            Control.OnTouchEvent(e.Event);
        }
    }
}

Posts

Sign In or Register to comment.