在Html.fromHtml()之后删除额外的换行符

Ale*_*euk 35 html android line-breaks spanned

我试图将html放入TextView.一切都很完美,这是我的代码.

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

这将我的TextView设置为正确的html.但我的问题是,有一个

在html中的标签中,进入TextView的结果文本末尾有一个"\n",因此它将我的TextView的高度推高到应有的高度.

由于它是一个Spanned变量,我不能应用正则表达式替换来删除"\n",如果我将它转换为字符串,然后应用正则表达式,我失去了使html锚点正常工作的功能.

有没有人知道从"跨越"变量中删除结束换行符的任何解决方案?

Lor*_*rte 51

很好的答案@Christine.我写了一个类似的函数来从CharSequence中删除尾随空格今天下午:

/** 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);
}
Run Code Online (Sandbox Code Playgroud)


Chr*_*ine 20

spannable是CharSequence,你可以操作它.

这有效:

    myTextView.setText(noTrailingwhiteLines(html));

    private CharSequence noTrailingwhiteLines(CharSequence text) {

        while (text.charAt(text.length() - 1) == '\n') {
            text = text.subSequence(0, text.length() - 1);
        }
        return text;
    }


小智 7

你可以试试这个:

Spanned htmlDescription = Html.fromHtml(textWithHtml);
String descriptionWithOutExtraSpace = new String(htmlDescription.toString()).trim();

textView.setText(htmlDescription.subSequence(0, descriptionWithOutExtraSpace.length()));
Run Code Online (Sandbox Code Playgroud)

  • 将 Spanned 对象转换为 String 不会丢失跨度吗? (5认同)