[FIXED] Custom WebView working in simulator but not in physical device. Xamarin

Issue

I have implemented a custom web view renderer in Droid project. The issue is, Custom WebView working in simulator but not in physical device.

In physical device WebView load only 1st time not in second time. Even though the android version is same, the physical device and the simulator have different results.

  public class MyWebViewRenderer : WebViewRenderer
    {
        public MyWebViewRenderer(Context context) : base(context) { }
        static MyWebView _xwebView = null;
        WebView _webView;
       
        class ExtendedWebViewClient : Android.Webkit.WebViewClient
        {
            public override async void OnPageFinished(WebView view, string url)
            {
                if (_xwebView != null)
                {
                    int i = 10;
                    while (view.ContentHeight == 0 && i-- > 0) 
                        await System.Threading.Tasks.Task.Delay(10);
                    _xwebView.HeightRequest = view.ContentHeight;
                }
                base.OnPageFinished(view, url);
               
            }
        }

        protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
        {
            base.OnElementChanged(e);
            _xwebView = e.NewElement as MyWebView;
            _webView = Control;

            if (e.OldElement == null)
            {
                _webView.SetWebViewClient(new ExtendedWebViewClient());
              
            }
        }

    }

Any help is appreciated. Thanks!

Solution

I have tested it on the Xiaomi MI 6X Android 9 again. It can still work well, no matter how many times I got into the webview.

So I suggest you download the android studio to check the logs when you get into the webview 2nd time.

You can also try to test it on the different devices which have different android version.

Answered By – Liyun Zhang – MSFT

Answer Checked By – Willingham (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published