我有简单的HTML:

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

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


当前回答

如果您试图从字符串资源id显示HTML,则格式可能不会显示在屏幕上。如果发生这种情况,请尝试使用CDATA标记:

strings.xml:
<string name="sample_string"><![CDATA[<h2>Title</h2><br><p>Description here</p>]]></string>

...

MainActivity.java:
text.setText(Html.fromHtml(getString(R.string.sample_string));

有关更多详细信息,请参阅本文。

其他回答

您可以使用Github上的HtmlDsl库为Android TextView构建有效的HTML:https://github.com/jaredrummler/HtmlDsl.

该库只支持Android提供的元素和属性,提供语法糖,使代码更容易理解,更不容易出错。

创建一些HTML的示例:

textView.setHtml {
    h3("Android Versions:")
    ul {
        li {
            a(href = "https://developer.android.com/about/versions/12/get") {
                +"Android 12 Beta"
            }
        }
        li("Android 11")
        li("Android 10")
        li("Pie")
        li("Oreo")
        li("Nougat")
        li("Marshmallow")
        li("Lollipop")
        // ...
    }

    small {
        sub {
            +"by "
            a {
                href = "https://github.com/jaredrummler"
                text = "Jared Rummler"
            }
        }
    }
}

Android TextView支持的HTML元素:

<a href="...">
<b>
<big>
<blockquote>
<br>
<cite>
<dfn>
<div align="...">
<em>
<font color="..." face="...">
<h1>
<h2>
<h3>
<h4>
<h5>
<h6>
<i>
<img src="...">
<p>
<small>
<strike>
<strong>
<sub>
<sup>
<tt>
<u>
<ul>
<li>

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

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

(new HtmlSpanner()).fromHtml()

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

使用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}"
        ...

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

它也很好!!

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

它只适用于少数标签。

需要使用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)
}