我有简单的HTML:
<h2>Title</h2><br>
<p>description here</p>
我想在TextView中显示HTML样式的文本。如何做到这一点?
我有简单的HTML:
<h2>Title</h2><br>
<p>description here</p>
我想在TextView中显示HTML样式的文本。如何做到这一点?
当前回答
为strings.xml文件中的字符串使用CData部分以在TextView中实际显示html内容的最佳方法。下面的代码片段将为您提供大致思路。
//in string.xml file
<string name="welcome_text"><![CDATA[<b>Welcome,</b> to the forthetyroprogrammers blog Logged in as:]]> %1$s.</string>
//and in Java code
String welcomStr=String.format(getString(R.string.welcome_text),username);
tvWelcomeUser.setText(Html.fromHtml(welcomStr));
即使在使用string.format方法格式化文本之后,字符串文本中的CData部分也会保持html标记数据的完整性。因此,Html.fromHtml(str)工作正常,您将在欢迎消息中看到粗体文本。
输出:
欢迎来到您最喜爱的音乐应用商店。登录身份:username
其他回答
需要使用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)
}
下面的代码给了我最好的结果。
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}"
...
简单地使用
checkBoxTextView.text =
Html.fromHtml("<p><font color=#666666>I agree to</font><font color=#0173B7> <b><u>Terms & Conditions</u></b></font><font color=#666666> and the <u></font><b><font color=#0173B7>Privacy Policy</font></u></b></font></p>")
我还想建议以下项目:https://github.com/NightWhistler/HtmlSpanner
用法与默认的android转换器几乎相同:
(new HtmlSpanner()).fromHtml()
在我已经开始自己实现html到可扩展转换器之后发现了它,因为标准html.fromHtml在渲染控制上没有足够的灵活性,甚至不可能使用ttf中的自定义字体