Image for post
Image for post
Illustration by Virginia Poltrack

Underspanding spans

Florina Muntenescu
Apr 4, 2018 · 9 min read

Under the hood: how spans work

Setting text for maximum performance

1. Text set on a TextView never changes

2. Text style changes by adding/removing spans

textView.setText(spannableObject, BufferType.SPANNABLE)
// if setText was called with BufferType.SPANNABLE
textView.setText(spannable, BufferType.SPANNABLE)
// the text can be cast to Spannable
val spannableText = textView.text as Spannable
// now we can set or remove spans
spannableText.setSpan(
ForegroundColorSpan(color),
8, spannableText.length,
SPAN_INCLUSIVE_INCLUSIVE)

3. Text changes (reusing TextView)

val spannableFactory = object : Spannable.Factory() {
override fun newSpannable(source: CharSequence?): Spannable {
return source as Spannable
}
}
textView.setSpannableFactory(spannableFactory)

Bonus performance tip

class MainActivity : AppCompatActivity() {
// keeping the span as a field
val bulletSpan = BulletPointSpan(color = Color.RED)
override fun onCreate(savedInstanceState: Bundle?) {

val spannable = SpannableString(“Text is spantastic”)
// setting the span to the bulletSpan field
spannable.setSpan(
bulletSpan,
0, 4,
Spanned.SPAN_INCLUSIVE_INCLUSIVE)
styledText.setText(spannable)
button.setOnClickListener( {
// change the color of our mutable span
bulletSpan.color = Color.GRAY
// color won’t be changed until invalidate is called
styledText.invalidate()
}
}

Under the hood: passing text with spans intra and inter-process

// start Activity with text with spans
val intent = Intent(this, MainActivity::class.java)
intent.putExtra(TEXT_EXTRA, mySpannableString)
startActivity(intent)
// read text with Spans
val intentCharSequence = intent.getCharSequenceExtra(TEXT_EXTRA)

Android Developers

The official Android Developers publication on Medium

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store