Maybe this isn't a bug since the documentation doesn't say much about what fromHTML()
exactly does, but it's a problem for me nonetheless. If the provided string contains two or more spaces in sequence, fromHTML()
removes all but one:
Html.fromHtml("Test 123").toString()
(java.lang.String) Test 123
If I replace the spaces with
it seems to behave as expected, but causes me grief in other parts of my program:
Html.fromHtml("Test 123").toString()
(java.lang.String) Test 123
Is this expected behavior?
Yes it is because that's how Html behaves.
Do something like this:
String myText = "Test 123";
Html.fromHtml(myText.replace(" ", " ")).toString()
This way, it preserves the original value of your string.
This is how HTML normally handles rendering of whitespace.
From the HTML Spec (emphasis mine):
Note that a sequence of white spaces between words in the source document may result in an entirely different rendered inter-word spacing (except in the case of the PRE element). In particular, user agents should collapse input white space sequences when producing output inter-word space. This can and should be done even in the absence of language information
The goal of the fromHtml
function is to visually render the text based on the contained HTML, so it makes sense that it will follow HTML rendering rules as closely as possible.
If you'd like to preserve white space exactly, you could see if fromHtml()
supports the <pre>
tag?
Best approach works for me 100%
This answer works but cause side effect on some tag styles like <font color=#FFFFFF>Text</font>
To solve this problem just ignore one spaces with this way:
// htmlText = "This is test";
public String fixDoubleSpaceIssue(String htmlText)
{
htmlText= text.replace(" ", " ");
htmlText= text.replace(" ", " ");
return htmlText;
}
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