Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Html.fromHTML removes double space

Tags:

android

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?

like image 930
Mike Lowery Avatar asked May 01 '13 01:05

Mike Lowery


3 Answers

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.

like image 78
dannyroa Avatar answered Nov 13 '22 21:11

dannyroa


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?

like image 37
Kiirani Avatar answered Nov 13 '22 20:11

Kiirani


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("   ", "&nbsp;&nbsp;&nbsp;");
    htmlText= text.replace("  ", "&nbsp;&nbsp;");
    return htmlText;
}
like image 2
Amir Hossein Ghasemi Avatar answered Nov 13 '22 19:11

Amir Hossein Ghasemi