Html.fromHtml后删除多余的换行符()多余、换行符、Html、fromHtml

2023-09-05 08:36:43 作者:Hypoxia.(缺氧)

我试图把HTML到一个TextView。一切完美的作品,这是我的code。

I am trying to place html into a TextView. Everything works perfectly, this is my code.

String htmlTxt = "<p>Hellllo</p>"; // the html is form an API
Spanned html = Html.fromHtml(htmlTxt);
myTextView.setText(html);

这集我的TextView使用正确的HTML。但我的问题是,有在HTML中的

标签,即进入TextView的结果文本具有一个\ N结尾,所以它推动我的TextView的身高高于它应该是。

This sets my TextView with the correct html. But my problem is, having a

tag in the html, the result text that goes into the TextView has a "\n" at the end, so it pushes my TextView's height higher than it should be.

自跨区变量,我不能申请正则表达式替换删除\ N的,如果我是把它转换成一个字符串,然后应用正则表达式,我失去使用HTML锚正常工作的功能

Since its a Spanned variable, I can't apply regex replace to remove the "\n", and if I was to convert it into a string, then apply regex, I lose the functionality of having html anchors to work properly.

没有人知道任何解决方案,以从​​跨区变量中删除结尾换行符(S)?

Does anyone know any solutions to remove the ending linebreak(s) from a "Spanned" variable?

推荐答案

尼斯答案@Christine。我写了一个类似的功能从CharSequence中删除尾随空白今天下午:

Nice answer @Christine. I wrote a similar function to remove trailing whitespace from a CharSequence this afternoon:

/** Trims trailing whitespace. Removes any of these characters:
 * 0009, HORIZONTAL TABULATION
 * 000A, LINE FEED
 * 000B, VERTICAL TABULATION
 * 000C, FORM FEED
 * 000D, CARRIAGE RETURN
 * 001C, FILE SEPARATOR
 * 001D, GROUP SEPARATOR
 * 001E, RECORD SEPARATOR
 * 001F, UNIT SEPARATOR
 * @return "" if source is null, otherwise string with all trailing whitespace removed
 */
public static CharSequence trimTrailingWhitespace(CharSequence source) {

    if(source == null)
        return "";

    int i = source.length();

    // loop back to the first non-whitespace character
    while(--i >= 0 && Character.isWhitespace(source.charAt(i))) {
    }

    return source.subSequence(0, i+1);
}