The problem: given HTML formatted input, display the normal text with a custom font and special tags with another custom font.

To apply custom fonts Calligraphy is my preferred helper library.

3 custom fonts in one TextView

It works great to apply one font to one TextView. It has CalligraphyTypefaceSpan to apply fonts to a range of characters. It has all the tools you need, you just need to know how to use them.

If you happen to know the position of the text you want to highlight, just follow the example Calligraphy provides:

Having the input in HTML means you have to locate the formatting, get the position of the characters you need to highlight, remove the formatting, adjust the position, apply spans to the characters.

Doable, but terribly inefficient. Much better to do piggy back on the standard android HTML parsing and just adjust the parts you want.

The SpannableStringBuilder allows easy editing of all of Android’s spans. For a full list of spans, see subclasses in CharacterStyle.

Grab the spans you are want to adjust from SpannableStringBuilder.

StyleSpan formats the font, With a custom font it’s creating fake bold and fake italic characters from the regular characters. If kept, it would apply extra weight to your already bold font. It must go and be replaced by CalligraphyTypefaceSpan.

Other spans can be kept, you add extra formatting on top. In the example we make SuperscriptSpan have a smaller font size by adding RelativeSizeSpan to the same characters.

Share

Leave a comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.

More blogs