Robby Smet
Robby Smet

Reputation: 4661

Linebreaks are ignored in Html.fromHtml

I receive a text with linebreaks from an API but I can't get the linebreaks to work.

This is a part of the text I want to shown. http://pastebin.com/CLnq16mP (pasted it there because the formatting on stackoverflow wasnt correct.)

I tried this:

termsAndConditionsTextView.setText(Html.fromHtml("<html><body>" + textResponse.getText() + "</body></html>"));

and this:

termsAndConditionsTextView.setText(Html.fromHtml(textResponse.getText()));

but the linebreaks (\r\n) and spaces are always ignored.

How can I fix this?

Upvotes: 6

Views: 4545

Answers (2)

Joop Eggen
Joop Eggen

Reputation: 109547

As the text is pre-formatted, even with indentation, you could use the <pre> tag.

<pre>
   your text.
</pre>

But the newlines evidently where escaped: \r\n so you still have to convert:

message = message.replace("\\r\\n", "\r\n");

The same holds for \/.

If you want to introduce bold, hyperlinks and such, then the <pre> tag fails, as it can only contain preformatted as-is text,

Upvotes: 4

DejanRistic
DejanRistic

Reputation: 2039

Since its html try using

</br>

You can replace all \r\n and spaces in your text by doing something like this:

    //message is your string.

    message = message.replace("\r\n","<br />");
    message = message.replace(" ","&nbsp;");
    termsAndConditionsTextView.setText(Html.fromHtml(message));

Good Luck!

Upvotes: 15

Related Questions