如何在 TextView 中显示 HTML? [英] How to display HTML in TextView?

查看:29
本文介绍了如何在 TextView 中显示 HTML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有简单的HTML:

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

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

I want to display HTML styled text it in TextView. How to do this?

推荐答案

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

You need to use Html.fromHtml() to use HTML in your XML Strings. Simply referencing a String with HTML in your layout XML will not work.

这是你应该在 Java 中做的事情

This is what you should do in 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 中:

And in Kotlin:

textView.text = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    Html.fromHtml(html, Html.FROM_HTML_MODE_COMPACT)
} else {
    Html.fromHtml(html)
}

这篇关于如何在 TextView 中显示 HTML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆