Spannable Text in Jetpack Compose

Syed Hussain Mehdi
2 min readSep 2, 2021

--

Since, everything is updated day by day. In Android Development it is common. We need keep update ourself with new technologies and updates.

Earlier XML was our best friend to make UI in android. Now a new friend join us as Jetpack Compose.

Jetpack Compose is Declarative UI, Its make easy to developed and design UI.

As new things comes up we also face kinds of problem. I’m going to write about on simple problem How to make Spannable Text in Compose?

And, Yes Compose make it really easy.

To create a TextView in Compose we use Text.

e.g

Text(text = "This is my text")

Text is overloaded method its accept either String or AnnotatedString.

To create spannable we have to create AnnotatedString.

Let’s take a text e.g “I have read Terms and Condition” in this String i want to color Terms and Condition text.

val annotatedString = buildAnnotatedString {
append("I have read")
withStyle(style = SpanStyle(Color.Blue)) {
append(" Terms and Condition")
}
}

We can do something like this. buildAnnotatedString {} We will put our string inside this scope with append() method.

To giving style of text with put append() method in withStyle(){} scope.

And then just pass annotatedString into Text().

e.g

@Composable
fun SpannableText() {
val annotatedString = buildAnnotatedString {
append("I have read")
withStyle(style = SpanStyle(Color.Blue)) {
append(" Terms and Condition")
}
}

Text(text = annotatedString)
}

Now in this example we have just seen how we can span our text using AnnotatedString.

In the second article I’ll discuss how we can add Click on Spannable Text.

Please don’t forget to follow for next article :) Happy Coding.

--

--