我有简单的HTML:
<h2>Title</h2><br>
<p>description here</p>
我想在TextView中显示HTML样式的文本。如何做到这一点?
我有简单的HTML:
<h2>Title</h2><br>
<p>description here</p>
我想在TextView中显示HTML样式的文本。如何做到这一点?
当前回答
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));
}
其他回答
如果在项目中使用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更好,因为代码更少-只有一行代码,建议使用它。
下面的代码给了我最好的结果。
TextView myTextview = (TextView) findViewById(R.id.my_text_view);
htmltext = <your html (markup) character>;
Spanned sp = Html.fromHtml(htmltext);
myTextview.setText(sp);
使用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}"
...
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));
}
创建Kotlin扩展以从字符串转换html-
fun String?.toHtml(): Spanned? {
if (this.isNullOrEmpty()) return null
return HtmlCompat.fromHtml(this, HtmlCompat.FROM_HTML_MODE_COMPACT)
}