Html.fromHTML removes double space

This may not be a mistake, as the documentation does not say what exactly fromHTML() does, but this is a problem for me nonetheless. If the provided string contains two or more spaces in the sequence, fromHTML() removes all but one:

 Html.fromHtml("Test 123").toString() (java.lang.String) Test 123 

If I replaced the spaces with   , it appears to be behaving as expected, but it makes me sad in other parts of my program:

 Html.fromHtml("Test  123").toString() (java.lang.String) Test 123 

Is this the expected behavior?

+4
source share
5 answers

This is how HTML typically handles the rendering of spaces.

From HTML Spec ( emphasis ):

Note that a sequence of spaces between words in a document source may lead to a completely different spacing provided by the interconnect (except in the case of the PRE element). In particular, user agents must collapse the input white space sequences when producing the output interlayer space. This can and should be done even in the absence of language information


The purpose of the fromHtml function is to visually visualize text based on the contained HTML, so it makes sense that it will comply with HTML rendering rules as much as possible.

If you want to preserve blank space exactly, you can see if fromHtml() supports the <pre> ?

+2
source

Yes, this is because HTML behaves.

Do something like this:

 String myText = "Test 123"; Html.fromHtml(myText.replace(" ", "&nbsp;")).toString() 

Thus, it saves the original value of your string.

+7
source

as Html.fromHtml uses the same rules that the browser uses to parse HTML, yes, it is expected that several spaces are flushed to one for that matter and any other HTML link .

0
source

Best approach works for me 100%

This answer works, but causes a side effect for some tag styles like <font color=#FFFFFF>Text</font>

To solve this problem, simply ignore one space as follows:

 // htmlText = "This is test"; public String fixDoubleSpaceIssue(String htmlText) { htmlText= text.replace(" ", "&nbsp;&nbsp;&nbsp;"); htmlText= text.replace(" ", "&nbsp;&nbsp;"); return htmlText; } 
0
source

I used the following and it worked!

myText = myText.replaceAll(" ", "%20"); myText = Html.fromHtml(myText).toString(); myText = myText.replaceAll("%20", " ");

-3
source

All Articles