机器人的WebView正确处理在pformatted $ P $文本换行机器人、正确处理、换行、文本

2023-09-05 07:16:45 作者:封心爱人

如果我把这个HTML到的WebView

If I push this HTML into WebView:

webView.loadData("<html><body><pre>line 1\nline 2</pre></body></html>", "text/html", "utf-8");

它呈现为(模拟器中,也对设备)

it renders as (in emulator and also on device)

line 1line 2

,而不是

line 1
line 2

因为我期望的那样。如果我保存这个HTML到SD卡,并在浏览器中打开该文件,它呈现的罚款。我想我做错了什么,或者这可能是一个错误。任何方式,我希望通过编程与preformatted新行推HTML到一个的WebView 并有换行符呈现。

as I would expect. If I save this HTML to the sdcard and open the file in the browser, it renders fine. I suppose I am doing something wrong, or this may be a bug. Any way, I want to programatically push HTML with preformatted newlines into a WebView and have the newlines rendered.

推荐答案

传递给 loadData 的字符串必须是URI转义。

The string passed to loadData needs to be URI-escaped.

您可以使用 URLEn coder.en code()要做到这一点,但由于某些原因的WebView 不c中的+。一个解决办法是更换所有的+%20自己。

You can use URLEncoder.encode() to do that, but for some reason WebView does not decode the '+' back to a ' '. One work around is to replace all the '+' with '%20' yourself.

例如(并与+译文):

try {
    webview.loadData(URLEncoder.encode("<html><body><pre>line 1\nline 2</pre></body></html>", "utf-8").replaceAll("\\+", "%20"), "text/html", "utf-8");
} catch (UnsupportedEncodingException uee) {
    Log.e("webview", "", uee);
}