Search code examples
xamarin.formswebviewxamarin.androidandroid-webviewcustom-renderer

Web page height correctly rendered with WebViewRenderer, but not with ViewRenderer<HybridWebView, Android.Webkit.WebView>


There is something different between the default WebViewRenderer and my custom ViewRenderer and I have to find out why. Basically, the web page isn't displayed if I use my custom ViewRenderer.

The ViewRenderer has some issues with height: 100%; and interprets this CSS wrong. As result the height is 0px, despite it should use the full height. On the other side it works with exact sizes (e.g. 400px).

Code for WebViewRenderer:

<local:CustomWebView x:Name="webView"
     Source="http://somesite"
     HorizontalOptions="FillAndExpand"
     VerticalOptions="FillAndExpand"
     HeightRequest="1000"
     WidthRequest="1000"/>
public class CustomWebView : WebView
{
}

public class CustomWebViewRenderer : WebViewRenderer
{
    public CustomWebViewRenderer(Context context) : base(context)
    {

    }
}

Code for ViewRenderer:

<local:HybridWebView x:Name="webView"
                     HorizontalOptions="FillAndExpand"
                     VerticalOptions="FillAndExpand"
                     HeightRequest="1000"
                     WidthRequest="1000"/>
public class HybridWebView : View
{
}

public class HybridWebViewRenderer : ViewRenderer<HybridWebView, Android.Webkit.WebView>
{
    private Context context;

    public HybridWebViewRenderer(Context context) : base(context)
    {
        this.context = context;
    }

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

        if (Control == null)
        {
            var webView = new Android.Webkit.WebView(this.context);
            webView.Settings.JavaScriptEnabled = true;
            webView.SetWebViewClient(new CustomWebViewClient());
            SetNativeControl(webView);
        }

        if (e.OldElement != null)
        {
        }

        if (e.NewElement != null)
        {
            Control.LoadUrl("http://somesite");
        }
    }
}

public class CustomWebViewClient : WebViewClient
{

}

One assumption is that the responsive website adapts to its WebView size, and since the rendering process takes place in background it somehow has a height of zero at this time.


Solution

  • I don't know why, but this solves the issue for me:

    webView.LayoutParameters = new LinearLayout.LayoutParams(LayoutParams.MatchParent, LayoutParams.MatchParent);
    

    If anyone has a clue, please comment.