我有简单的HTML:

<h2>Title</h2><br>
<p>description here</p>

我想在TextView中显示HTML样式的文本。如何做到这一点?


当前回答

我知道这个问题很老了。这里的其他答案建议使用Html.fromHtml()方法。我建议您使用androidx.core.text.HtmlCompat包中的HtmlCompat.fromHtml()。因为这是Html类的向后兼容版本。

示例代码:

import androidx.core.text.HtmlCompat;
import android.text.Spanned;
import android.widget.TextView;

String htmlString = "<h1>Hello World!</h1>";

Spanned spanned = HtmlCompat.fromHtml(htmlString, HtmlCompat.FROM_HTML_MODE_COMPACT);

TextView tvOutput = (TextView) findViewById(R.id.text_view_id);

tvOutput.setText(spanned);

通过这种方式,您可以避免Android API版本检查,并且它很容易使用(单行解决方案)。

其他回答

如果在项目中使用androidx.*类,则应使用HtmlCompat.fromHtml(文本,标志)。

方法来源:

@NonNull
    public static Spanned fromHtml(@NonNull String source, @FromHtmlFlags int flags) {
        if (Build.VERSION.SDK_INT >= 24) {
            return Html.fromHtml(source, flags);
        }
        //noinspection deprecation
        return Html.fromHtml(source);
    }

使用HtmlCompat.fromHtml比使用Html.fromHtml更好,因为代码更少-只有一行代码,建议使用它。

简单使用Html.fromHtml(“Html字符串”)。这会奏效的。如果字符串具有类似<h1>的标记,则空格将出现。但我们无法消除这些空间。如果仍要删除空格,则可以删除字符串中的标记,然后将字符串传递给Html.fromHtml(“Html string”);方法。通常,这些字符串也来自服务器(动态),但如果将字符串原样传递给方法比从字符串中删除标记更好,则不经常这样做。

看看这个:https://stackoverflow.com/a/8558249/450148

它也很好!!

<resource>
    <string name="your_string">This is an <u>underline</u> text demo for TextView.</string>
</resources>

它只适用于少数标签。

您可以像这样使用简单的Kotlin扩展函数:

fun TextView.setHtmlText(source: String) {
    this.text = HtmlCompat.fromHtml(source, HtmlCompat.FROM_HTML_MODE_LEGACY)
}

和用法:

textViewMessage.setHtmlText("Message: <b>Hello World</b>")
String value = html value ....
mTextView.setText(Html.fromHtml(value),TextView.BufferType.SPANNABLE)