本文主要是介绍记自己遇到的一些WebView坑,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
记自己遇到的一些WebView坑
1. 坑1
这个bug遇到的时候不是必现。
WebView加载时设置了这样的语句会加载白页:
webView.loadData("", "text/html", "uft-8");
例如:
webView.loadData("", "text/html", "uft-8");
//...<other code>...webView1.loadUrl(url);
//...<other code>...@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.iv_goback:if (webView.canGoBack()) {//此时此处canGoBack()有一定几率为true 导致返回为白页webView.goBack();//返回上一浏览页面} else {finish();//关闭Activity}}}
我的配置代码
@Override
protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_html5_bottom_bar);mProgressBar = (ProgressBar) findViewById(R.id.progressBar);mProgressBar.setMax(100);
}
private void requestData(String url) {WebSettings webSettings = webView.getSettings();webSettings.setDefaultTextEncodingName("utf-8");webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);//不使用缓存webView.setWebChromeClient(new MyChromeClient());webSettings.setBuiltInZoomControls(false); // 放大缩放按钮// 如果访问的页面中有JavaScript,则WebView必须设置支持JavaScriptwebSettings.setJavaScriptEnabled(true);//JS交互webView.addJavascriptInterface(new JsInteration(), "control");// 设置可以支持缩放webSettings.setSupportZoom(true);// 扩大比例的缩放webSettings.setUseWideViewPort(true);webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);webSettings.setLoadWithOverviewMode(true);webView.setWebViewClient(new WebViewClient() {public boolean shouldOverrideUrlLoading(WebView view, String url) { // 重写此方法表明点击网页里面的链接还是在当前的webview里跳转,不跳到浏览器那边view.loadUrl(url);return true;}@Overridepublic void onPageStarted(WebView view, String url, Bitmap favicon) {super.onPageStarted(view, url, favicon);isShowFail = false;}@Overridepublic void onPageFinished(WebView view, String url) {super.onPageFinished(view, url);if (!isShowFail) { customview.showLoadStateView(CustomView.STATE_NONE);}}@Overridepublic void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {super.onReceivedError(view, errorCode, description, failingUrl);isShowFail = true;customview.showLoadStateView(CustomView.STATE_ERROR);// 加载失败时显示的失败界面}});webView.loadUrl(url);
}
//与JS交互的对象
public class JsInteration {@JavascriptInterfacepublic void gotoGoodInfo(String id){//doSomething}
}
// 设置加载进度
public class MyChromeClient extends android.webkit.WebChromeClient {@Overridepublic void onProgressChanged(WebView view, int newProgress) {mProgressBar.setProgress(newProgress);if (newProgress == 100) {mProgressBar.setVisibility(View.GONE);} else {mProgressBar.setVisibility(View.VISIBLE);}super.onProgressChanged(view, newProgress);}@Overridepublic void onReceivedTitle(WebView view, String title) {//获取加载的url的标题super.onReceivedTitle(view, title);}
}
陆续更新,博客新人欢迎评论╮( ̄▽ ̄”)╭
这篇关于记自己遇到的一些WebView坑的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!