详解Android WebView加载html片段

作者:袖梨 2022-06-25

这里我先简单描述一下需求:服务器返回的是html页面的一部分带有标签的内容。

解决的思路是:将服务器返回的内容片段拼凑成一个完整的页面。

下面直接上核心代码:

这里是WebView一些配置

WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setDomStorageEnabled(true);
settings.setUseWideViewPort(true);
settings.setLoadWithOverviewMode(true);
webView.setWebViewClient(new MyWebViewClient(activity));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {    
 settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING);
} else {
 settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
}
webView.loadData(getHtmlData(item.content), "text/html;charset=utf-8","utf-8");
private String getHtmlData(String bodyHTML) {
    String head = "" +
        "html{padding:15px;} body{word-wrap:break-word;font-size:13px;padding:0px;margin:0px} p{padding:0px;margin:0px;font-size:13px;color:#222222;line-height:1.3;} img{padding:0px,margin:0px;max-width:100%; width:auto; height:auto;}" +
        "";
    return "" + head + "" + bodyHTML + "";
  }
 
static class MyWebViewClient extends WebViewClient{
    private WaitingDialog dialog;
    private Activity activity;
    public MyWebViewClient(Activity activity){
      dialog = new WaitingDialog(activity);
      this.activity = activity;
    }
 
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
      LogUtil.e(url);
      view.loadUrl(url);
      return true;
    }
 
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
      super.onPageStarted(view, url, favicon);
      if(!activity.isFinishing()) dialog.show();
    }
 
    @Override
    public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
      handler.proceed();
      super.onReceivedSslError(view, handler, error);
    }
 
    @Override
    public void onPageFinished(WebView view, String url) {
      super.onPageFinished(view, url);
      if(!activity.isFinishing()) dialog.dismiss();
    }

笔者在Nexus6 7.0上面测试偶尔出现,html内容无法加载出来,显示一片空白,开启硬件加速后完美解决。

在上面WebView设置的部分加上如下代码

if (webView.isHardwareAccelerated()) settings.setJavaScriptEnabled(true)

相关文章

精彩推荐