webView加载html图片遇到的问题解决

当解析接口 突然出现一个xml形式的html格式的字符串的时候不用慌张,正常去交给webview的loaddata方法来解决即可,但是今天说的是一组图片字符串


         
         
         
         
         
         

因为给出的网址不包含http:// 所以怎么解都解不出来的 我们只需要拼接一下这个数据 然后在利用jsoup来适配一下屏幕即可

implementation 'org.jsoup:jsoup:1.10.2'

解析方法

    public static String formatHtml(String str){
//        String httpStr="";
//        String divStr="
$content
"; // String ulStr="
    $ul
"; String[] split = str.split(">"); StringBuffer sb = new StringBuffer(); for (int i = 0; i < split.length; i++) { String replace = split[i].replace(""); // sb.append("
  • "+ replace +">"+"
  • "); } // ulStr=ulStr.replace("$ul", sb.toString()); // divStr=divStr.replace("$content", ulStr); return sb.toString(); }

    当时是想着吧该html片段还原一个标准的div嵌套无序列表的形式 结果发现不用这么麻烦依然好用 下面是代码

      //  content就是哪个html数据
           String content = t1.getData().getContent();
      //进行拼接http:
                String s = formatHtml(content);
    //jsoup适配屏幕大小
                Document doc = Jsoup.parse(s);
    
                Elements elem_img = doc.getElementsByTag("img");
    // 图片自适应屏幕
                if (elem_img.size() != 0) {
                    for (Element el_img : elem_img) {
                        el_img.attr("style", "width:100%");
                    }
                }
    //适配之后转换回字符串
                String s1 = doc.toString();
    
    //以下这些设置不用设置 设置效果也不如jsoup适配后的效果
    //            WebSettings settings = webView.getSettings();
    //            settings.setJavaScriptEnabled(true);
    //            settings.setUseWideViewPort(true);//关键点
    //            settings.setLoadWithOverviewMode(true);
     //在webview内部打开浏览器
                webView.setWebViewClient(new WebViewClient());
    //            settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
    //            settings.setDefaultTextEncodingName("utf-8") ;
    //以下俩种方式效果一样 用哪个都行
                webView.loadData(s1, "text/html","utf-8");
    //            webView.loadDataWithBaseURL(null,s1, "text/html",  "utf-8", null);
                Log.i("tag", "subjectPage 1Result: "+s);

    以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

    你可能感兴趣的:(webView加载html图片遇到的问题解决)