Android: How to combine Spannable.setSpan with String.format?

getText() will return SpannedString objects that contain the formatting defined in strings.xml. I have created a custom version of String.format that will preserve any spans in the format string, even of they enclose format specifiers (spans in SpannedString arguments are also preserved). Use it like this:

Spanned toDisplay = SpanFormatter.format(getText(R.string.foo), bar, baz, quux);

I solved this by introducing TaggedArg class, instances of this class expands to <tag>value</tag>. Then I created object that is responsible for reading text containing tags and replacing these tags by spans. Different spans are registered in map tag->factory.

There was one little surprise. If you have text like "<xx>something</xx> something", Html.fromHtml reads this text as "<xx>something something</xx>". I had to add tags <html> around whole text to prevent this.

Leave a Comment