WebView更改错误显示页面之WebChromeClient

来源:互联网 发布:皮带轮怎样数控车编程 编辑:程序博客网 时间:2024/06/05 01:07

最近项目中UI提了一个小要求自定义WebView的错误显示页面,于是上网查资料后发现要在WebViewClient的onReceivedError()的方法里面进行修改

like this

mWebView.setWebViewClient(new WebViewClient(){    @SuppressWarnings("deprecation")    @Override    public void onReceivedError(WebView view,int errorCode, String description, String failingUrl){        super.onReceivedError(view,errorCode,description,failingUrl);        view.loadUrl("file///android_asset/showError.html");//加载本地的Html文件作为错误显示页面
    }});
可是WebChrome并没有onReceivedError这个方法!下面我们来看看WebViewClient和WebChromeClient的常用方法和区别?

ANDROID应用开发的时候可能会用到WEBVIEW这个组件,使用过程中可能会接触到WEBVIEWCLIENT与WEBCHROMECLIENT,那么这两个类到底有什么不同呢?
WebViewClient主要帮助WebView处理各种通知、请求事件的,比如:

onLoadResource
onPageStart
onPageFinish
onReceivedError 
onReceivedHttpAuthRequest

WebChromeClient主要辅助WebView处理Javascript的对话框、网站图标、网站title、加载进度等比如

onCloseWindow(关闭WebView)
onCreateWindow()
onJsAlert (WebView上alert无效,需要定制WebChromeClient处理弹出)
onJsPrompt
onJsConfirm
onProgressChanged
onReceivedIcon
onReceivedTitle
看上去他们有很多不同,实际使用的话,如果你的WebView只是用来处理一些html的页面内容,只用WebViewClient就行了,如果需要更丰富的处理效果,比如JS、进度条等,就要用到WebChromeClient。
更多的时候,你可以这样


WebView webView;
webView= (WebView) findViewById(R.id.webview);
webView.setWebChromeClient(new WebChromeClient());
webView.setWebViewClient(new WebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
这样你的WebView理论上就能有大部分需要实现的特色了
当然,有些更精彩的内容还是需要你自己添加的

那么具体如何实现呢?很简单在你获取数据之前进行判断,如果无网络就直接加载本地html文件,
步骤:
在工程中新建一个文件放入html文件,具体代码中引用
protected void loadData() {    if (!NetWorkUtils.isNetConnected(BaseApplication.getAppContext())) {        mwebView.loadUrl("file///android_asset/showError.html")//要按照这种格式书写路径才正确    } else {
}


这样即可实现类似这种效果

或者如果你想在onReceivedError方法种加载错误提示页面也是可以的,

mVideoEnabledWebView.setWebChromeClient(mVideoEnabledWebChromeClient);//设置WebChromeClient后继续设置WebViewClient
mVideoEnabledWebView.setWebViewClient(new WebViewClient() {    @SuppressWarnings("deprecation")    @Override    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {        super.onReceivedError(view, errorCode, description, failingUrl);        // TIME_OUT或者是手机无网络访问时加载本地网页        view.loadUrl("file:///android_asset/showError");    }});

原创粉丝点击