我有简单的HTML:

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

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


当前回答

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

它也很好!!

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

它只适用于少数标签。

其他回答

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

值得一提的是,从API级别24开始,Html.fromHtml(字符串源代码)方法已被弃用。如果这是你的目标API,你应该使用Html.fromHtml(字符串源,int标志)。

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

我已经使用web视图实现了这一点。在我的例子中,我必须从URL加载图像以及文本视图中的文本,这对我很有用。

WebView myWebView =new WebView(_context);
        String html = childText;
        String mime = "text/html";
        String encoding = "utf-8";
        myWebView.getSettings().setJavaScriptEnabled(true);
        myWebView.loadDataWithBaseURL(null, html, mime, encoding, null);

setText(Html.fromHtml(bodyData))在api 24之后被弃用。现在你必须这样做:

 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
      tvDocument.setText(Html.fromHtml(bodyData,Html.FROM_HTML_MODE_LEGACY));
 } else {
      tvDocument.setText(Html.fromHtml(bodyData));
 }