Style certain parts of Compose Text
4 min readMar 12, 2023
In this article, we will learn about styling certain parts of the text using the extension function.
Here is our extension function
/**
* @param textToStyle provide part of the text to style
* @param spanStyle apply style to passed text if we can find the index of that part,
* NOTE: It will apply style for all occurrences
*/
fun CharSequence.applyStyLeForAll(
textToStyle: String,
spanStyle: SpanStyle = SpanStyle(fontStyle = FontStyle.Italic)
): AnnotatedString {
var startIndex = 0
var index = this.indexOf(textToStyle, startIndex)
val annotatedString = buildAnnotatedString {
while (index >= 0) {
append(this@applyStyLeForAll.substring(startIndex, index))
pushStyle(spanStyle)
append(textToStyle)
pop()
startIndex = index + textToStyle.length
index = this@applyStyLeForAll.indexOf(textToStyle, startIndex)
}
append(this@applyStyLeForAll.substring(startIndex, this@applyStyLeForAll.length))
}
return annotatedString
}
Advantage
- We can use this extension globally
- We can apply different types of styling with just two parameters.
i.e Bold, Italic, Underline, etc - Easy to use
Disadvantage
- We need to pass part of the text. If we are using the multilingual app then we need to create separate strings So it will apply style for different languages…