我有简单的HTML:

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

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


当前回答

使用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));

每当您编写自定义文本视图时,基本的HTML设置文本功能将从某些设备上消失。

因此,我们需要执行以下附加步骤,使其有效

public class CustomTextView extends TextView {

    public CustomTextView(..) {
        // other instructions
        setText(Html.fromHtml(getText().toString()));
    }
}

需要使用Html.fromHtml()在XML字符串中使用Html。在布局XML中简单地引用带有HTML的字符串是行不通的。

这是在Java中应该做的

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    textView.setText(Html.fromHtml("<h2>Title</h2><br><p>Description here</p>", Html.FROM_HTML_MODE_COMPACT));
} else { 
    textView.setText(Html.fromHtml("<h2>Title</h2><br><p>Description here</p>"));
}

在Kotlin:

textView.text = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    Html.fromHtml(html, Html.FROM_HTML_MODE_COMPACT)
} else {
    Html.fromHtml(html)
}
String value = html value ....
mTextView.setText(Html.fromHtml(value),TextView.BufferType.SPANNABLE)

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

它也很好!!

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

它只适用于少数标签。