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?
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?
It has been suggested through various answers to use the Html framework class as suggested here, but unfortunately this class has different behavior in different versions of Android and various unaddressed bugs, as demonstrated in issues 214637, 14778, 235128 and 75953.
You may therefore want to use a compatibility library to standardize and backport the Html class across Android versions which includes more callbacks for elements and styling:
While it is similar to the framework's Html class, some signature changes were required to allow more callbacks. Here's the sample from the GitHub page:
May I suggest a somewhat hacky but still genius solution! I got the idea from this article and adapted it for Android. Basically you use a
WebView
and insert the HTML you want to show and edit in an editable div tag. This way when the user taps theWebView
the keyboard appears and allows editing. They you just add some JavaScript to get back the edited HTML and voila!Here is the code:
And here is the component as a Gist.
Note: I didn't need the height change callback from the original solution so that's missing here but you can easily add it if needed.
If you just want to display some html text and don't really need a
TextView
, then take aWebView
and use it like following:This does not restrict you to a few html tags either.
The below code gave best result for me.
The best approach to use CData sections for the string in strings.xml file to get a actual display of the html content to the TextView the below code snippet will give you the fair idea.
CData section in string text keeps the html tag data intact even after formatting text using String.format method. So, Html.fromHtml(str) works fine and you’ll see the bold text in Welcome message.
Output: