WebView顶级适配方案 图片,style等全适配,支持二级修改等

2021/04/07 14:58:03

webview基本设置:

private static void initWebSettings(WebView mWebView) {
        if (mWebView != null) {
            WebSettings settings = mWebView.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setLoadWithOverviewMode(true);
            settings.setUseWideViewPort(true);
            settings.setBuiltInZoomControls(false);
            settings.setSupportZoom(true);
            settings.setPluginState(WebSettings.PluginState.OFF);
            settings.setDomStorageEnabled(true);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
            }
            settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
            mWebView.setWebViewClient(new WebViewClient());
            mWebView.setWebChromeClient(new WebChromeClient());
        }
    }

webview加载方案:

    public static void setWebViewUrl(WebView webView, String url) {
        if (TextUtils.isEmpty(url)) return;
        initWebSettings(webView);
        if (url.startsWith("http")) {
            webView.loadUrl(url);
        } else {
            webView.getSettings().setTextZoom(250);//web 文字适配 默认值为100也就是不放大字体
            webView.loadData(getNewContent(url), "text/html;charset=UTF-8", null);
        }
//        webView.loadData(webUrl, "text/html;charset=UTF-8", null);
    }

内容解析及替换:

private static String getNewContent(String htmltext) {
        Document doc = Jsoup.parse(htmltext);
        //图片适配
        Elements elements = doc.getElementsByTag("img");
        for (Element element : elements) {
            element.attr("width", "100%").attr("height", "auto");
        }

        //style 中的属性适配
        Elements elementsP = doc.select("[style]");
        for (Element element : elementsP) {
            String content = element.attr("style");
            element.attr("style", setAttribute(content, "width", "100%"));
//            element.attr("width", "100%").attr("height", "auto");
        }
        return doc.toString();
    }

针对style里的二级属性进行设置:

 

private static String setAttribute(String content, String attributeKey, String value) {
        if (!content.contains(attributeKey)) {
            return content;
        }
        String s1 = content.substring(0, content.indexOf(attributeKey));
        String s2 = content.substring(content.indexOf(attributeKey), content.length());
        String s3 = s2.substring(s2.indexOf(";"));
        return s1 + attributeKey + ":" + value + s3;
    }

用到了第三方库 网页解析:jsoup

 //jsoup
    api 'org.jsoup:jsoup:1.11.2'