我的问题是如何处理此错误并用自己的自定义错误替换它。
您可以像下面的代码一样在WebViewClient中处理它,但它将用错误页替换整个WebView页面:
public class MyClient:WebViewClient
{
public Context _context;
public MyClient(Context c)
{
_context = c;
}
public override void OnReceivedError(WebView view, IWebResourceRequest request, WebResourceError error)
{
base.OnReceivedError(view, request, error);
var errMsg = error.DescriptionFormatted;
Toast.MakeText(_context, errMsg, ToastLength.Long).Show();
string htmlData = $"<html><body><div align='center'>This is the description for the load fail : {errMsg}</div></body>";
view.LoadUrl("about:blank");
view.LoadDataWithBaseURL(null, htmlData, "text/html", "UTF-8", null);
view.Invalidate();
}
...
或者,您可以在Html中处理错误,您可以定义一个与webview大小相同的错误窗口,并根据internet状态隐藏/显示它:
<DOCTYPE>
<html>
<head></head>
<body>
<iframe id="mFrame" width="854" height="480" src="https://www.youtube.com/embed/a5GMRrEJaVo" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
<div id="errorWindow" width="854" height="480">
This is the div for your custom error view
</div>
<script>
(function(){
"use strict"
var mIframe=document.getElementById("mFrame");
var errorWindow=document.getElementById("errorWindow");
if(navigator.onLine)
{
//internet available
mIframe.hidden=false;
errorWindow.hidden=true;
}else
{
//internet not available
mIframe.hidden=true;
errorWindow.hidden=false;
}
})()
</script>
</body>
注意:您必须定义以下权限才能
navigator.onLine
工作:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />