我有简单的HTML:
<h2>Title</h2><br>
<p>description here</p>
我想在TextView中显示HTML样式的文本。如何做到这一点?
我有简单的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>
它只适用于少数标签。
其他回答
String value = html value ....
mTextView.setText(Html.fromHtml(value),TextView.BufferType.SPANNABLE)
人们已经为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>"
... />
如果您只想显示一些html文本,而实际上不需要TextView,那么使用WebView,如下所示:
String htmlText = ...;
webview.loadData(htmlText , "text/html; charset=UTF-8", null);
这也不会限制您使用几个html标记。
值得一提的是,从API级别24开始,Html.fromHtml(字符串源代码)方法已被弃用。如果这是你的目标API,你应该使用Html.fromHtml(字符串源,int标志)。
下面的代码给了我最好的结果。
TextView myTextview = (TextView) findViewById(R.id.my_text_view);
htmltext = <your html (markup) character>;
Spanned sp = Html.fromHtml(htmltext);
myTextview.setText(sp);