How to display HTML in TextView?

I have simple HTML :

<h2>Title</h2><br>
<p>description here</p>

I want to display HTML styled text it in TextView . How to do this?


You need to use Html.fromHtml() to use HTML in your XML Strings. Simply referencing a String with HTML in your layout XML will not work.

For example (< Android Nougat):

myTextView.setText(Html.fromHtml("<h2>Title</h2><br><p>Description here</p>"));

For example (>= Android Nougat):

myTextView.setText(Html.fromHtml("<h2>Title</h2><br><p>Description here</p>", Html.FROM_HTML_MODE_COMPACT));

To distinguish between Android versions use Build.VERSION.SDK_INT >= Build.VERSION_CODES.N .


Have a look on this: https://stackoverflow.com/a/8558249/450148

It is pretty good too!!

<resource>
    <string name="your_string">This is an <u>underline</u> text demo for TextView.</string>
</resources>

It works only for few tags.


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));
 }
链接地址: http://www.djcxy.com/p/32012.html

上一篇: 如何访问Android Wear中的心率传感器?

下一篇: 如何在TextView中显示HTML?