androidresourcesspannable

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


I'm setting Span to part of the text. Span itself works well. However, the text is created by String.format from Resources and I do not know start and end of part in the text I'm going to set Span to.

I tryed to use custom HTML tags in strings.xml, but either getText or getString remove them. I could use something like this getString(R.string.text, "<nb>" + arg + "</nb>"), then Html.fromHtml(), because the arg is exactly where i want to set the Span.

I seen this approach that used text formatted "normal text ##span here## normal text". It parses the string removes tags and sets Span.

Is there a better way to set Span into a formatted string like "something %s something" or should I use one of the above approaches?


Solution

  • 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.