我有简单的HTML:
<h2>Title</h2><br>
<p>description here</p>
我想在TextView中显示HTML样式的文本。如何做到这一点?
我有简单的HTML:
<h2>Title</h2><br>
<p>description here</p>
我想在TextView中显示HTML样式的文本。如何做到这一点?
当前回答
人们已经为TextView、WebView和各种解决方案建议了子类。我想知道为什么没有人提到一个简单的绑定适配器。
@BindingAdapter(value = ["htmlText"])
fun TextView.setHtmlText(string: String?) {
text = HtmlCompat.fromHtml(string?:"", HtmlCompat.FROM_HTML_MODE_COMPACT)
}
因此,您的TextView xml将如下所示
<TextView
...
htmlText="<p>Your <b>HTML</b> text</p>"
... />
其他回答
创建一个全局方法,如:
public static Spanned stripHtml(String html) {
if (!TextUtils.isEmpty(html)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return Html.fromHtml(html, Html.FROM_HTML_MODE_COMPACT);
} else {
return Html.fromHtml(html);
}
}
return null;
}
您也可以在“活动/片段”中使用它,如:
text_view.setText(stripHtml(htmlText));
看看这个:https://stackoverflow.com/a/8558249/450148
它也很好!!
<resource>
<string name="your_string">This is an <u>underline</u> text demo for TextView.</string>
</resources>
它只适用于少数标签。
人们已经为TextView、WebView和各种解决方案建议了子类。我想知道为什么没有人提到一个简单的绑定适配器。
@BindingAdapter(value = ["htmlText"])
fun TextView.setHtmlText(string: String?) {
text = HtmlCompat.fromHtml(string?:"", HtmlCompat.FROM_HTML_MODE_COMPACT)
}
因此,您的TextView xml将如下所示
<TextView
...
htmlText="<p>Your <b>HTML</b> text</p>"
... />
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));
}
String value = "<html> <a href=\"http://example.com/\">example.com</a> </html>";
SiteLink= (TextView) findViewById(R.id.textViewSite);
SiteLink.setText(Html.fromHtml(value));
SiteLink.setMovementMethod(LinkMovementMethod.getInstance());