Spantastic text styling with Spans

To style text in Android, use spans! Change the color of a few characters, make them clickable, scale the size of the text or even draw custom bullet points with spans. Spans can change the TextPaint properties, draw on a Canvas, or even change text layout and affect elements like the line height. Spans are markup objects that can be attached to and detached from text; they can be applied to whole paragraphs or to parts of the text.

Let’s see how to use spans, what spans are provided out of the box, how to easily create your own and finally how to test them:

Styling text in Android

Applying spans

Framework spans

Creating custom spans

Testing custom spans implementation

Testing spans usage

Styling text in Android

Android offers several ways of styling text:

  • Single style — where the style applies to the entire text displayed by a TextView
  • Multi style — where several styles can be applied to a text, at character or paragraph level

Single style implies styling of the entire content of the TextView, using XML attributes or styles and themes. This approach is an easy solution and works from XML but doesn’t allow styling of parts of the text. For example, by setting textStyle=”bold”, the entire text will be bold; you can’t define only specific characters to be bold.

Read More