Xamarin Forms WebView Crashes for Android when used with Forms Embedding
I reproduced your problem when I transfer a Xamarin.Forms Page(which contain a WebView) to Fragment, and here is a workaround :
You could put a native android Android.Webkit.WebView in a Fragment, then you could display this Fragment to implement the same feature.
Create a WebViewFragment :
public class WebViewFragment : Fragment
{
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
var view = inflater.Inflate(Resource.Layout.webview_in_fg, container, false);
WebView fg_webview = view.FindViewById<WebView>(Resource.Id.fg_webview);
fg_webview.SetWebViewClient(new MyWebViewClient());
fg_webview.Settings.JavaScriptEnabled = true;
fg_webview.LoadUrl("http://developer.xamarin.com");
return view;
}
}
public class MyWebViewClient : WebViewClient
{
public override bool ShouldOverrideUrlLoading(WebView view, string url)
{
view.LoadUrl(url);
return true;
}
public override void OnPageStarted(WebView view, string url, Android.Graphics.Bitmap favicon)
{
base.OnPageStarted(view, url, favicon);
}
public override void OnPageFinished(WebView view, string url)
{
base.OnPageFinished(view, url);
}
public override void OnReceivedError(WebView view, ClientError errorCode, string description, string failingUrl)
{
base.OnReceivedError(view, errorCode, description, failingUrl);
}
}
Create a WebView layout :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="@+id/fg_webview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Replace your WebViewPage with the WebViewFragment :
//Fragment webViewPage = new WebViewPage().CreateFragment(mainActivity);
Fragment webViewPage = new WebViewFragment();