Xamarin Webview'网页不可用'错误,如何显示自定义错误消息

时间:2017-07-29 11:26:16

标签: xamarin webview error-handling xamarin.android

这是行动代码。

namespace LoadWebPage {
    [Activity(Label = "LoadWebPage", MainLauncher = true, Icon = "@drawable/icon", Theme = "@android:style/Theme.NoTitleBar")]
    public class Activity1 : Activity {
        protected override void OnCreate (Bundle bundle)
        {
            base.OnCreate (bundle);

            // Set our view from the "main" layout resource
            SetContentView (Resource.Layout.Main);

            // Get our webview and load the local file in for display
            WebView webView = FindViewById<WebView>(Resource.Id.LocalWebView);
            webView.SetWebViewClient (new WebViewClient ());
            webView.LoadUrl("http://www.xamarin.com");

            // Some websites will require Javascript to be enabled
            webView.Settings.JavaScriptEnabled = true;
            //webView.LoadUrl("http://youtube.com");

            // allow zooming/panning            
            webView.Settings.BuiltInZoomControls = true;
            webView.Settings.SetSupportZoom(true);

            // scrollbar stuff            
            webView.ScrollBarStyle = ScrollbarStyles.OutsideOverlay; 
            // so there's no 'white line'            
            webView.ScrollbarFadingEnabled = false;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

子类WebViewClient并实现两个OnReceivedError方法,然后创建WebViewClient子类的实例,并通过WebView.SetWebViewClient方法分配它。

当您收到错误时,发布原生AlertDialog,自定义弹出窗口或将WebView重定向到自定义错误页面等...

WebViewClient子视图:

public class Client : WebViewClient
{
    public override void OnReceivedError(WebView view, ClientError errorCode, string description, string failingUrl)
    {
        DisplayError(view, description);
    }

    // API 21+
    public override void OnReceivedError(WebView view, IWebResourceRequest request, WebResourceError error)
    {
        DisplayError(view, error.Description);
    }

    void DisplayError(WebView view, string description)
    {
        Toast.MakeText(view.Context, description, ToastLength.Long).Show();
        view.LoadUrl("https://stackoverflow.com");
    }
}

用法:

webView.SetWebViewClient(new Client());