How to preserve HTML in formatted strings

Android TextView widgets can display formatted text — <b>, <i>, hyperlinks, etc. — but the formatting is stripped away if you pass the string through String.format(), or if you do any concatenation on the string.

Tip # 1: To preserve HTML formatting, you need to URL encode the text so the formatting code is preserved, and then use Html.fromHtml() to re-convert it.

// context.getString() uses String.format() when you pass more than one parameter
final String aboutText = context.getString(R.string.about_dialog_main_text, info.versionName);

TextView textView = (TextView) view.findViewById(;

// use the LinkMovementMethod to make links clickable

// convert the URL-encoded text back into real formatted text

Tip # 2: Passing text through String.format() also strips out any \n sequences, so wherever you want newlines you’ll need to use the HTML <br> code instead.

Interestingly, if you’re using strings from an XML string resource, you only need to URL encode the leading < sign to &lt; like so:

original string:

Version %1$s

Developed by ...

encoded string:

<b>Version %1$s</b><br><br>Developed by <b><a href="...">...</a></b>

My guess is that the > sign isn’t a special character in format strings, so it doesn’t need to be encoded.


Share on facebook
Share on twitter
Share on pinterest
Share on linkedin

Leave a Reply

Your email address will not be published. Required fields are marked *

On Key

Related Posts


5 Passive Income Ideas

If you’ve been looking for smart ways to make money in 2020 and beyond, this article is for you. At Andromo, we’re all about making