Spannable Strings in Android

Article

TJ Dahunsi

Jul 08 2016 · 2 mins

Categories:
design

Spans and Spannable Strings in Android are a lovely concept. They provide a layer of abstraction over any Android widget that displays text, which allows you to have complex formatting in your text without you having to resort to using a webview with tedious HTML or multiple concatenated TextViews or whatever widget you're using.

Managing spans however can be difficult. Each span must specify where it starts, ends and creating news spans on the fly using their default constructors can be annoying. 

After scouring the Android's docs and Stack-Overflow, I came upon some very handy utility methods, applied the Builder Pattern to them and came up with my very own SpanUtils class.

The SpanBuilder lets you create a simple span from any Charsequence and prepend any Charsequence (that may be spanned itself) while preserving formatting. It also provides a similar String.format method for spanned Strings as well.

Some methods rely on the use of a static Application context in the App, which requires the extension of Android's default Application class. I realize not everyone likes to do this, so for those methods the context may simply be passed in as an extra argument as the class doesn't hold a reference to it internally.

Example usage of the class includes:

int pointsAwarded = getArguments().getInt(POINTS_AWARDED); CharSequence text = SpanUtils.spanBuilder( SpanUtils.spanBuilder("") .prependCharsequence("+" + pointsAwarded) .resize(1.5F) .build() ) .prependCharsequence(getString(R.string.bonus)) .build();

With the resulting image:

And another:

CharSequence updateText = SpanUtils.spanBuilder(tierValues[i]) .resize(1.8f) .bold() .build(); dynamicTextSequence[i] = SpanUtils.format(staticTextSequence[i], updateText);

In this case, the value of the percentage is a dynamic value pulled in from the backend hence the use of the format method. The arrays are only used because the text displayed is dynamic and cycles through an array of values.

In the class gist embedded below, some methods make use of String resources. The resources  are:

<string name="apply\_brackets"\>(%1$s)</string\> <string name="prepend\_number"\>%1$d %2$s</string\> <string name="prepend\_string"\>%1$s %2$s</string\>
,