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
as opposed to
line 1
line 2
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.
The string passed to loadData
needs to be URI-escaped.
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.
For example (and with the '+'
translation):
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);
}
Try this:
webView.loadDataWithBaseURL(...)
More info here
Also you can use
chapterWebView.loadDataWithBaseURL("file:///android_asset/NTImages/", message.replaceAll("\\n", "<br/>") , "text/html", "utf-8", "utf-8");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With