private void initWebView() {
settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
// webview.addJavascriptInterface(this, "Android");
webview.getSettings().setSupportZoom(true);
webview.getSettings().setTextZoom(100);
webview.setWebViewClient(new WebViewClient(){
//页面加载的时候调用,通常显示一个进度条
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url,favicon);
//设定加载开始的操作
Utils.showProgress(SignActivity.this);
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
Utils.hideProgress(SignActivity.this);
}
//返回值是true的时候是控制网页在WebView中去打开,如果为false调用系统浏览器或第三方浏览器打开
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
//6.0以下执行
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl){
showErrorPage();
}
//处理网页加载失败时
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
//6.0以上执行
showErrorPage();//显示错误页面
}
});
webview.loadUrl(url);
webParentView = (LinearLayout) webview.getParent(); //获取父容器
}
/***
* 显示加载失败时自定义的网页
*/
private void initErrorPage() {
if (mErrorView == null) {
mErrorView = View.inflate(this, R.layout.layout_load_error, null);
}
}
/**
* 显示自定义错误提示页面,用一个View覆盖在WebView
*/
private void showErrorPage() {
webParentView.removeAllViews(); //移除加载网页错误时,默认的提示信息
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
webParentView.addView(mErrorView, 0, layoutParams); //添加自定义的错误提示的View
}
layout_load_error
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/load_error_layout" android:layout_width="match_parent" android:layout_height="match_parent"> <!--加载网页错误的提示图--> <ImageView android:id="@+id/error_iv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:contentDescription="@null" android:src="@mipmap/no_data" /> <!--点击提示文字,重新加载网页--> <TextView android:id="@+id/reload_tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/error_iv" android:layout_centerHorizontal="true" android:layout_marginTop="8dp" android:gravity="center" android:text="数据获取失败\n, 请检查网络后再重试 ~~~" /></RelativeLayout>
在oncreat里调用
initWebView(); initErrorPage();
记录
over
因篇幅问题不能全部显示,请点此查看更多更全内容