记自己遇到的一些WebView坑
1. 坑1
这个bug遇到的时候不是必现。
WebView加载时设置了这样的语句会加载白页:
webView.loadData("", "text/html", "uft-8");
例如:
webView.loadData("", "text/html", "uft-8");
//...<other code>...
webView1.loadUrl(url);
//...<other code>...
@Override
public 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必须设置支持JavaScript
webSettings.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;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
isShowFail = false;
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (!isShowFail) {
customview.showLoadStateView(CustomView.STATE_NONE);
}
}
@Override
public 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 {
@JavascriptInterface
public void gotoGoodInfo(String id){
//doSomething
}
}
// 设置加载进度
public class MyChromeClient extends android.webkit.WebChromeClient {
@Override
public 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);
}
@Override
public void onReceivedTitle(WebView view, String title) {
//获取加载的url的标题
super.onReceivedTitle(view, title);
}
}
陆续更新,博客新人欢迎评论╮( ̄▽ ̄”)╭