Android

How to preserve HTML in formatted strings

By July 27, 2011August 8th, 2011No Comments

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(R.id.about_app);

// use the LinkMovementMethod to make links clickable
textView.setMovementMethod(LinkMovementMethod.getInstance());

// convert the URL-encoded text back into real formatted text
textView.setText(Html.fromHtml(aboutText));

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.