Set TextView text from html-formatted string resource in XML
Instantly set HTML in TextView using:
Include HTML in strings.xml like a pro using CDATA:
Html.fromHtml()
, the charmer, transforms HTML into Spannable text for your TextView.
Dealing with HTML special characters
It's not always sunshine and rainbows with HTML:
- Some characters like ' (apostrophe), " (double-quote), & (ampersand) got the 'special' tag and need to be escaped.
- Ampersand appears as
&
just to make things tad bit harder.
Android version compatibility
Handling HTML in different Android versions:
- Prior to Android N (API 24),
Html.fromHtml()
was enough. - Post-Nougat, switch to Markdown or use flags with
Html.fromHtml()
for consistently good looks. - Remember to check the room before dancing!
Build.VERSION.SDK_INT
helps check the Android API level.
Custom Classes and Attributes
Introduce subclassed TextViews for the VIP treatment:
Better than using an Activity for a TextView
, right?
Say No to Deprecated Methods
Android updates: The bane of a developer's existence.
- Move to
HtmlCompat.fromHtml()
from the AndroidX library. - Make sure your
strings.xml
is in step with Android's updated recommendations.
Unearthing Undocumented Methods
Off-the-beaten-path methods and techniques can be found in community forums or bug trackers. They're like hidden Easter eggs in a game!
Third-party Libraries to the Rescue
Sometimes, the built-in tools just don't cut it:
- Markwon: For displaying Markdown in
TextView
, the new black in formatting text. - RichTextView libraries: They make it easy to parse and display HTML and Markdown.
Fancy Text Styling
The butler of TextView
โ HTML tags in strings.xml
:
- Style your text using
bold
, italics,underlined
and more. - Use getText() instead of
getString()
. Why? So your stylish text doesn't lose its charm.
Custom TextView for the Win
Unlock a powerful ally with a custom TextView. It lets you control how HTML is handled, reducing code repetition.
Was this article helpful?