Spannable Text in Jetpack Compose — Android

Chintan Rathod
CodeAndroid
Published in
2 min readJul 22, 2024

The life of an Android developer has become much easier with the advent of Jetpack Compose in Android development. However, there are still areas that require significant knowledge

Although in the traditional Android View system using XML, we could use “SpannableString” to achieve the desired output in the “TextView”, “SpannableString” is not supported in Jetpack Compose.

How to create Spannable Text in Jetpack Compose?

To create Spannable Text in Compose is very easy and straightforward.

As you know, to create a TextView in Compose, you need to write following code.

Eg.

Text (text = "This is sample text")

Here, text argument is overloaded with String and AnnotatedString and as you guess correctly, AnnotatedString is the alternative to SpannableString.

Change Style

To change style, like color, in the String, you can use following example.

Suppose we have the string “I accept Privacy Policy” and we want to highlight “Privacy Policy” with Blue. We can achieve this by using “buildAnnotatedString” function and applying styles as needed.

val annotatedString = buildAnnotatedString {
append("I accept")
withStyle(style = SpanStyle(Color.Blue)) {
append(" Privacy Policy")
}
}

Text(text = annotatedString)

Change Text Size

There could be a case that we want to either make font/text size bigger or smaller in our string.

Taking an example of “Google Pixel at 50% Discount”. Well that’s a huge discount but in example, we want to make 50% Discount” at slightly bigger size to previous text.

Following example will allow you to make it work.

val annotatedString = buildAnnotatedString {
withStyle(style = SpanStyle(fontSize = 15.sp)) {
append("Google Pixel at")
}
withStyle(style = SpanStyle(fontSize = 20.sp)) {
append(" 50% Discount")
}
}

Text(text = annotatedString)

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

Happy Coding.

--

--

Chintan Rathod
CodeAndroid

Sr. Mobile Developer (#AndroidDev) | Kotlin Fan | Writer | Self learner | Blogger : www.chintanrathod.com.