Android WebView无法正确加载本地HTML字符串

3

我正在开发一个项目,需要在 WebView 中显示一些 HTML 字符串。问题是这些 HTML 字符串只包含 body 部分,没有任何像 <html>, <head>, <body> 这样的标签。当我尝试在 WebView 中显示接收到的字符串时,结果会显示从服务器接收到的 HTML 字符串中包含的标签。

以下是我所接收到和所做的一些示例:

从服务器接收到的 HTML 字符串:

05-30 14:02:56.785: D/(16970): body : &lt;p align=&#039;justify&#039;&gt;The so-called Fiscal Compact is unlikely to be approved by the Latvian parliament in the second and final reading as four opposition MPs said that they would not back the initiative, local media reported on Tuesday evening. The second reading is scheduled for May 31. Under local legislation, the bill should be backed by 67 MPs in the 100-seat parliament, though the ruling coalition controls only 56 seats and depends on the opposition Union of Greens and Farmers (ZZS) to approve it. During the first reading 68 MPs backed the bill. The four MPs from ZZS will meet PM Dombrovskis later today to discuss the issue. They want more clarity about the country&rsquo;s participation in neighboring Lithuania&rsquo;s nuclear power plant project. Previously, ZZS said it extends its support on condition that the government fights for higher subsidies for farmers in the 2014-2020 EU budget framework.&lt;/p&gt;

这是我的代码:

String bodyTxt = cursor.getString(cursor.getColumnIndex("body"));
Log.d("","body : "+bodyTxt);
String newBody = "<html><body>" + bodyTxt + "</body></html>";
body.loadDataWithBaseURL(null, newBody, "text/html", "utf-8", null);

结果如下所示:

result

我尝试使用 body.loadData(newBody, "text/html", "UTF-8"); ,但这种方式甚至没有显示结果。

所以有什么想法是我做错了什么,我该怎么解决?

谢谢!

3个回答

1

你可以使用这个

webview.loadData(Html.fromHtml(htmlData),"text/html","utf-8"); 

5
1oadData(String string, String string, String string) 不接受 Html.fromHtml(string),因为它返回一个 Spanned 对象。 - Matt

1

从您的日志中我可以看到,您收到的HTML标记不是使用<符号,而是像&gt;这样。我猜如果您在HTML字符串中替换这些字符,它应该会按预期工作。请尝试以下操作:

        String bodyTxt = cursor.getString(cursor.getColumnIndex("body"));
        String replaced = bodyTxt.replace("&lt;","<");
        Log.d("","replaced : "+replaced);
        String replaced2 = replaced.replace("&gt;", ">");
        Log.d("","replaced2 : "+replaced2);
        Log.d("","body : "+bodyTxt);
        String newBody = "<html><body>" + replaced2 + "</body></html>";
        body.loadDataWithBaseURL(null, newBody, "text/html", "utf-8", null);

0

这是我如何做的。

String htmlContent = "<html><body>hello</body></html>";
WebView wv = (WebView) findViewById(R.id.my_view);
wv.loadData(htmlContent, "text/html", "UTF-8");

调查数据库中数据的外观,所有的"<>"等都用"<"引用,这可能是你正在寻找的问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接