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

时间:2012-05-30 11:15:02

标签: android html android-webview

我正在开发一个项目,我收到一些html字符串,我应该在WebView中显示。问题是html字符串只包含正文部分,没有任何标记,如<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 个答案:

答案 0 :(得分:1)

你可以用这个

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

答案 1 :(得分:0)

我就是这样做的;

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

调查数据在数据库中的显示方式,所有“&lt;&gt;”这样引用“&lt;”,这可能是你要找的问题。

答案 2 :(得分:0)

正如我从您的日志中看到的那样,您收到的是不是<符号的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);