我有简单的HTML:

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

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


当前回答

我还想建议以下项目:https://github.com/NightWhistler/HtmlSpanner

用法与默认的android转换器几乎相同:

(new HtmlSpanner()).fromHtml()

在我已经开始自己实现html到可扩展转换器之后发现了它,因为标准html.fromHtml在渲染控制上没有足够的灵活性,甚至不可能使用ttf中的自定义字体

其他回答

人们已经为TextView、WebView和各种解决方案建议了子类。我想知道为什么没有人提到一个简单的绑定适配器。

@BindingAdapter(value = ["htmlText"])
fun TextView.setHtmlText(string: String?) {
    text = HtmlCompat.fromHtml(string?:"", HtmlCompat.FROM_HTML_MODE_COMPACT)
}

因此,您的TextView xml将如下所示

<TextView
   ...
   htmlText="<p>Your <b>HTML</b> text</p>"
   ... />

创建一个全局方法,如:

public static Spanned stripHtml(String html) {
            if (!TextUtils.isEmpty(html)) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    return Html.fromHtml(html, Html.FROM_HTML_MODE_COMPACT);
                } else {
                    return Html.fromHtml(html);
                }
            }
            return null;
        }

您也可以在“活动/片段”中使用它,如:

text_view.setText(stripHtml(htmlText));

使用BindingAdapter:

@BindingAdapter("renderHtml")
fun bindRenderHtml(view: TextView, description: String?) {
if (description != null) {
    view.text = HtmlCompat.fromHtml(description, FROM_HTML_MODE_COMPACT)
    view.movementMethod = LinkMovementMethod.getInstance()
} else {
    view.text = ""
}

}

用法:

  <TextView
        android:id="@+id/content_text_view"
        app:renderHtml="@{show.description}"
        ...

只需使用:

String variable="StackOverflow";
textView.setText(Html.fromHtml("<b>Hello : </b>"+ variable));
String value = html value ....
mTextView.setText(Html.fromHtml(value),TextView.BufferType.SPANNABLE)