loadData()中的html data中不能包含'#','%','\','?'四中特殊字符,出现这种字符就会出现解析错误,显示找不到网页还有部分HTML代码。我们需要用UrlEncoder编码为%23,%25,%27,%3f 。
例:
String linkCss = " <meta charset=\"utf-8\">\n" + " <meta name=\"viewport\" content=\"initial-scale=1, maximum-scale=1, user- scalable=no\">\n" +" <meta name=\"format-detection\" content=\"telephone=no\">"+"<style type=\"text/css\"> " +"img {" +"width:100%;" +"height:auto;" +"}" +"iframe{" +"width:100%;" +"height:auto;" +"}"+"p { margin: 0;padding: 0; }"+"body {" +"margin-right:0px;" +"margin-left:0px;" +"margin-top:0px;" +"margin-bottom:0px;" +"}" + "html{color:#C3C2BD;}" +"</style>";
String html ="<html><head>" + linkCss +"</head>" + bodyContent( html数据 )+"</body></html>";
webView.loadData(html, "text/html", "uft-8");
可以使用以下两种代码,data为string类型的HTML代码
1、webView.loadData(URLEncoder.encode(data,"utf-8"),"text/html", "utf-8");
这样加载的时候有时WebView无数据显示. 而且颜色并没有改变
String CSS_STYLE ="<style>* {font-size:16px;line-height:20px;}p {color:#C3C2BD;}</style>";
String linkCss = " <meta charset=\"utf-8\">\n" + " <meta name=\"viewport\" content=\"initial-scale=1, maximum-scale=1, user- scalable=no\">\n" +" <meta name=\"format-detection\" content=\"telephone=no\">"+"<style type=\"text/css\"> " +"img {" +"width:100%;" +"height:auto;" +"}" +"iframe{" +"width:100%;" +"height:auto;" +"}"+"p { margin: 0;padding: 0; }"+"body {" +"margin-right:0px;" +"margin-left:0px;" +"margin-top:0px;" +"margin-bottom:0px;" +"}" +"</style>";String html ="<html><head>" + linkCss +"</head>" + bodyContent( html数据 )+"</body></html>";
这里删除了 + "html{color:#C3C2BD;}"
webView.loadDataWithBaseURL(null, CSS_STYLE + html, "text/html","utf-8", null);
2、webView.loadDataWithBaseURL(null,data, "utf-8",null);
用loadDataWithBaseURL就可以解决了