我有简单的HTML:
<h2>Title</h2><br>
<p>description here</p>
我想在TextView中显示HTML样式的文本。如何做到这一点?
我有简单的HTML:
<h2>Title</h2><br>
<p>description here</p>
我想在TextView中显示HTML样式的文本。如何做到这一点?
当前回答
简单地使用
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>")
其他回答
使用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>")
public class HtmlTextView extends AppCompatTextView {
public HtmlTextView(Context context) {
super(context);
init();
}
private void init(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
setText(Html.fromHtml(getText().toString(), Html.FROM_HTML_MODE_COMPACT));
} else {
setText(Html.fromHtml(getText().toString()));
}
}
}
更新以上答案
简单使用Html.fromHtml(“Html字符串”)。这会奏效的。如果字符串具有类似<h1>的标记,则空格将出现。但我们无法消除这些空间。如果仍要删除空格,则可以删除字符串中的标记,然后将字符串传递给Html.fromHtml(“Html string”);方法。通常,这些字符串也来自服务器(动态),但如果将字符串原样传递给方法比从字符串中删除标记更好,则不经常这样做。
您可以使用Github上的HtmlDsl库为Android TextView构建有效的HTML:https://github.com/jaredrummler/HtmlDsl.
该库只支持Android提供的元素和属性,提供语法糖,使代码更容易理解,更不容易出错。
创建一些HTML的示例:
textView.setHtml {
h3("Android Versions:")
ul {
li {
a(href = "https://developer.android.com/about/versions/12/get") {
+"Android 12 Beta"
}
}
li("Android 11")
li("Android 10")
li("Pie")
li("Oreo")
li("Nougat")
li("Marshmallow")
li("Lollipop")
// ...
}
small {
sub {
+"by "
a {
href = "https://github.com/jaredrummler"
text = "Jared Rummler"
}
}
}
}
Android TextView支持的HTML元素:
<a href="...">
<b>
<big>
<blockquote>
<br>
<cite>
<dfn>
<div align="...">
<em>
<font color="..." face="...">
<h1>
<h2>
<h3>
<h4>
<h5>
<h6>
<i>
<img src="...">
<p>
<small>
<strike>
<strong>
<sub>
<sup>
<tt>
<u>
<ul>
<li>