首先正常操作
WebSettings webSettings = mBinding.wvText.getSettings();
webSettings.setJavaScriptEnabled(true); //支持js
webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
webSettings.setSupportZoom(true); //支持缩放,默认为true。是下面那个的前提。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING); //支持内容重新布局
else
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
webSettings.setAllowFileAccess(true); //设置可以访问文件
webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式
webSettings.setDomStorageEnabled(true);
webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
webSettings.setAppCacheEnabled(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setSupportMultipleWindows(true);
mBinding.wvText.setWebViewClient(new WebViewClient());
mBinding.wvText.setHorizontalScrollBarEnabled(false);
mBinding.wvText.setVerticalScrollBarEnabled(false);
给WebView设置一些基础的属性
然后用到一串代码加工富文本内容:
private String getHtmlData(String bodyHTML) {
String head = "<head>"
+ "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> "
+ "<style>img{max-width: 100%; width:100%; height:auto;}*{margin:0px;}</style>"
+ "</head>";
return "<html>" + head + "<body>" + bodyHTML + "</body></html>";
}
最后,在加载富文本时:
String bodyHTML = agreementEntityBaseData.getData().getContent(); //取得富文本信息
mBinding.wvText.loadData(getHtmlData(bodyHTML), "text/html; charset=UTF-8", null);
即可