Format TextView content with HTML tags
In most of the times, for displaying few lines of plain old text in Android application the TextView widget will be sufficient. What if you want to add a bit of text formatting to it? For example wrapping lines, making words bold or underlined, even adding some links to it.
It can be accomplished by providing HTML code to the TextView widget as text source.
Saving HTML code in Android app for reuse.
In case you are loading HTML source from resource files you have to either escape tags using the < notation or
simpler wrap whole source HTML code in
<![CDATA[ ... ]]>
section. Otherwise all the HTML tags are recognized and stripped out. It is also useful if
someone wants to store XML code inside string resource. With this approach also multiline text can be saved without
newline characters.
<string name="html_content" translatable="false">
<![CDATA[
<h1>H1 Title</h1>
<h2>H2 Title</h2>
<p>Paragraph<br>
New line<br>
<a href="http://rivancic.com">Supported links</a><br>
<b>Bold text</b><br>
<u>Underscore</u></p>
]]>
</string>
Setting HTML to TextView from code.
Populate the TextView with HTML content from code:
TextView htmlTv = (TextView) findViewById(R.id.html_tv);
htmlTv.setText(Html.fromHtml(getString(R.string.html_content)));
htmlTv.setMovementMethod(LinkMovementMethod.getInstance());
Html.fromHtml() method will return displayable text style for TextView. Underneath HTML content is parsed with
TagSoup. So this method gives its best to display your untrustable input.
If there are also some <a href="..."></a>
links included then user can also interact with them if we
TextView.setMovementMethod() ont TextView. This class then parses links and appends URI data to the Intent that is
then sent to system. So double check that URIs have proper format.
Be warned only limited set of tags is supported. Nice listed are on the Grokking Android page. The can be also found in source code in Html class source code.
For more complicated HTML formatting WebView component will be needed.