我有简单的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>"
... />
其他回答
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));
}
您可以使用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>
如果您希望能够通过xml配置它,而不需要对java代码进行任何修改,您可能会发现这个想法很有用。只需从构造函数调用init并将文本设置为html
public class HTMLTextView extends TextView {
... constructors calling init...
private void init(){
setText(Html.fromHtml(getText().toString()));
}
}
xml格式:
<com.package.HTMLTextView
android:text="@string/about_item_1"/>
每当您编写自定义文本视图时,基本的HTML设置文本功能将从某些设备上消失。
因此,我们需要执行以下附加步骤,使其有效
public class CustomTextView extends TextView {
public CustomTextView(..) {
// other instructions
setText(Html.fromHtml(getText().toString()));
}
}
如果在项目中使用androidx.*类,则应使用HtmlCompat.fromHtml(文本,标志)。
方法来源:
@NonNull
public static Spanned fromHtml(@NonNull String source, @FromHtmlFlags int flags) {
if (Build.VERSION.SDK_INT >= 24) {
return Html.fromHtml(source, flags);
}
//noinspection deprecation
return Html.fromHtml(source);
}
使用HtmlCompat.fromHtml比使用Html.fromHtml更好,因为代码更少-只有一行代码,建议使用它。