I came up with a slightly more flexible and reusable solution in my point of view, as the solutions quoted above are not working if we have several place holders
@Composable
fun annotateRecursively(
placeHolderList: List<Pair<String, SpanStyle>>,
originalText: String
): AnnotatedString {
var annotatedString = buildAnnotatedString { append(originalText) }
for (item in placeHolderList) {
annotatedString = buildAnnotatedString {
val startIndex = annotatedString.indexOf(item.first)
val endIndex = startIndex + item.first.length
append(annotatedString)
addStyle(style = item.second, start = startIndex, end = endIndex)
}
}
return annotatedString
}
This basically takes a list of Pair
precising the placeholder
and a SpanStyle
(instead of a Pair
it can be a custom data class
if you need anything else...)
Then iterate over the list
to annotate the string
with the corresponding SpanStyle
to their placeholder.