我有一个文章应用,我正在WebView
中显示文章。在Android版本8.1和9.0中,此WebView
不起作用。该应用程序在“活动”文章中显示NOTHING。
mWebView.setVisibility(View.VISIBLE);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.getSettings().setUseWideViewPort(true);
mWebView.getSettings().setMinimumFontSize(14);
String htmlContent = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"
+ "<head>"
+ "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />"
+ "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"/>"
+ "<style type=\"text/css\">body{color: #525252;} img {max-width: 100%; height: auto}</style>"
+ "</head>"
+ item.getContent() //content of item
+ "";
mWebView.loadData(htmlContent, "text/html; charset=utf-8", "UTF-8");
因此,我该如何解决这个问题?
我解决了我的问题,该问题发生在具有最新版Chrome的智能手机中。
SOLUTION:
请勿使用
mWebview.loadData
方法,而不是use
mWebview.loadDataWithBaseURL
因此,我的解决方案是:
mWebview.loadDataWithBaseURL(null,htmlContent,"text/html", "utf-8", null);
您的HTML内容应为Base64或URL编码。您的HTML示例中带有“#”,这会在某些WebView版本上引起问题。
这里是使用Base64编码的示例。
String htmlContent = "...";
String encodedHtml = Base64.encodeToString(htmlContent.getBytes(), Base64.NO_PADDING);
webView.loadData(encodedHtml, "text/html", "base64");
这里是javadoc以获取详细信息。
我在Android 9.0版中也遇到了同样的问题
[本页上的文档(https://developer.android.com/about/versions/pie/android-9.0-migration)提到:
[在Android 9中,用于Java语言的UTF-8解码器更加严格,遵循Unicode标准。
所以我尝试将UTF-8转换为Base64并使用loadData()
try {
String base64 = null;
base64 = android.util.Base64.encodeToString(lecureHtmlData.getBytes("UTF-8"),
android.util.Base64.DEFAULT);
wvLecture.loadData(base64, "text/html; charset=utf-8", "base64");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
现在它照常工作。
希望有帮助