Explain Codes LogoExplain Codes Logo

Set TextView text from html-formatted string resource in XML

java
html-engineering
android-development
textview
Nikita BarsukovbyNikita BarsukovยทDec 20, 2024
โšกTLDR

Instantly set HTML in TextView using:

// Because who has time to style by code ๐Ÿ˜„ textView.setText(Html.fromHtml(getString(R.string.html_string), Html.FROM_HTML_MODE_LEGACY));

Include HTML in strings.xml like a pro using CDATA:

<string name="html_string"><![CDATA[<b>Bold</b> text, <i>italics</i>]]></string>

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 &amp; 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:

public class HtmlTextView extends TextView { public HtmlTextView(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.HtmlTextView); String htmlText = a.getString(R.styleable.HtmlTextView_htmlText); if (htmlText != null) { // The Html class โ€” making your bland text fancy since 1995 ๐Ÿ˜Ž setText(Html.fromHtml(htmlText, Html.FROM_HTML_MODE_COMPACT)); } a.recycle(); } }

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.