Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML.fromHtml adds space at end of text?

Tags:

java

android

In my app I use the Html.fromHtml(string).toString method to remove some <p> tags that are received when I parse some JSON.

If I leave the <p> tags on, the text fits the background perfectly (the background is a relative layout with wrap_content in both height and width.) However, if I use fromHtml to remove the <p> tags, suddenely there is a huge space below the text, which I believe is the fromHtml method adding in space at the end?

Any ideas?

EDIT:

Here are screenshots: http://imgur.com/a/zIZNo

The one with <p> tags is the one that doesnt use fromHtml, obviously! :)

EDIT 2: Solution has been found, see my answer below. Thank you to Andro Selva for helping me by telling me about the hidden /n that was being added!

like image 627
Cameron W. Avatar asked Aug 09 '12 11:08

Cameron W.


3 Answers

Solution was found:

fromHtml returns the type Spanned. So I assigned what was being returned to a variable, converted it to a string and then used the .trim() method on it.

It removed all white space at the end.

like image 194
Cameron W. Avatar answered Nov 07 '22 19:11

Cameron W.


Yes what you thought about is really correct. It adds space to the bottom. But before that let me explain how this works.

You have to look at HTML class to see how it works.

To be simple, this is how it works: whenever your Html class looks at a <p> tag, what it does is simply append two "\n" chars to the end.

In this case the empty space you see at the bottom is actually because of the two \n appended to the end of the paragaraph.

And I have added the actual method of the Html class which is responsible for this action,

    private static void handleP(SpannableStringBuilder text) {
    int len = text.length();

    if (len >= 1 && text.charAt(len - 1) == '\n') {
        if (len >= 2 && text.charAt(len - 2) == '\n') {
            return;
        }
        text.append("\n");
        return;
    }

    if (len != 0) {

       text.append("\n\n");

    }
}

If you want to override this action, you have to override the Html class itself which is a bit tricky and can't be completed here.

EDIT

here is the link to the Html class,

Html class

like image 43
Andro Selva Avatar answered Nov 07 '22 19:11

Andro Selva


If you are trying to use it in an object or trying to fit it in a specific place, try using <a> tag instead of a <p>, <p> adds returns carriages at the end, a writes none, but you have to remember to write the \n yourself with <b>, and you get to keep the style

like image 3
BrianF Avatar answered Nov 07 '22 18:11

BrianF