我有简单的HTML:
<h2>Title</h2><br>
<p>description here</p>
我想在TextView中显示HTML样式的文本。如何做到这一点?
我有简单的HTML:
<h2>Title</h2><br>
<p>description here</p>
我想在TextView中显示HTML样式的文本。如何做到这一点?
当前回答
我还想建议以下项目:https://github.com/NightWhistler/HtmlSpanner
用法与默认的android转换器几乎相同:
(new HtmlSpanner()).fromHtml()
在我已经开始自己实现html到可扩展转换器之后发现了它,因为标准html.fromHtml在渲染控制上没有足够的灵活性,甚至不可能使用ttf中的自定义字体
其他回答
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()));
}
}
}
更新以上答案
使用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}"
...
看看这个:https://stackoverflow.com/a/8558249/450148
它也很好!!
<resource>
<string name="your_string">This is an <u>underline</u> text demo for TextView.</string>
</resources>
它只适用于少数标签。
下面的代码给了我最好的结果。
TextView myTextview = (TextView) findViewById(R.id.my_text_view);
htmltext = <your html (markup) character>;
Spanned sp = Html.fromHtml(htmltext);
myTextview.setText(sp);
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));
}