Question

I seem to be getting what seems like some extra line breaks after using this method to set the text of a TextView

message.setText(Html.fromHtml( message ));

How can I remove these? They cause my layout to get warped since it adds two extra lines to the output.

The string was saved to my sqlite database via Html.toHtml( editText.getText() ).trim();

Initial string input : hello

Log output of the message variable: <p dir="ltr">hello</p>

Était-ce utile?

La solution 3

Looks like toHtml assumes everything should be in a <p> tag. I'd strip off the beginning and ending <p> and </p> tags before writing to the database.

Autres conseils

you can use this lines ... totally works ;)

i know your problem solved but maybe some one find this useful .

 try{
        string= replceLast(string,"<p dir=\"ltr\">", "");
        string=replceLast(string,"</p>", "");
}catch (Exception e) {}

and here is replaceLast ...

public String replceLast(String yourString, String frist,String second)
{
    StringBuilder b = new StringBuilder(yourString);
    b.replace(yourString.lastIndexOf(frist), yourString.lastIndexOf(frist)+frist.length(),second );
    return b.toString();
}

For kotlin you can use

html.trim('\n')

This is working as below in Kotlin.

val myHtmlString = "<p>Test<\/p>"

HtmlCompat.fromHtml(myHtmlString.trim(), FROM_HTML_MODE_COMPACT).trim('\n')
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top