Skip to content

Instantly share code, notes, and snippets.

@mrmike
Created January 27, 2022 17:57
Show Gist options
  • Save mrmike/331aa7017fe912fad00f09fdf6ceb7d8 to your computer and use it in GitHub Desktop.
Save mrmike/331aa7017fe912fad00f09fdf6ceb7d8 to your computer and use it in GitHub Desktop.
Extension function for simpler annotated string creation with decoration in Jetpack Compose Compose
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.ParagraphStyle
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TtsAnnotation
fun AnnotatedString.Builder.appendDecorated(
text: String,
spanStyle: SpanStyle? = null,
paragraphStyle: ParagraphStyle? = null,
textAnnotation: TextAnnotation? = null,
ttsAnnotation: TtsAnnotation? = null,
) = withDecoration(spanStyle, paragraphStyle, textAnnotation, ttsAnnotation) { append(text) }
fun AnnotatedString.Builder.withDecoration(
spanStyle: SpanStyle? = null,
paragraphStyle: ParagraphStyle? = null,
textAnnotation: TextAnnotation? = null,
ttsAnnotation: TtsAnnotation? = null,
content: AnnotatedString.Builder.() -> Unit
) {
var popCount = 0
spanStyle?.let {
pushStyle(it)
popCount += 1
}
paragraphStyle?.let {
pushStyle(it)
popCount += 1
}
textAnnotation?.let {
pushStringAnnotation(tag = it.tag, annotation = it.annotation)
popCount += 1
}
ttsAnnotation?.let {
pushTtsAnnotation(it)
popCount += 1
}
this.content()
repeat(popCount) {
pop()
}
}
class TextAnnotation(val tag: String, val annotation: String)
@mrmike
Copy link
Author

mrmike commented Jan 27, 2022

Sample usage

@Composable
fun SampleUsage() {
    val text1 = buildAnnotatedString {
        withDecoration(
            spanStyle = SpanStyle(Color.Black, textDecoration = TextDecoration.Underline),
            textAnnotation = TextAnnotation("tag", "annotation")
        ) {
            append("Decorated text")
        }
    }

    val text2 = buildAnnotatedString {
        appendDecorated(
            text = "Decorated text",
            spanStyle = SpanStyle(Color.Blue, textDecoration = TextDecoration.Underline),
            textAnnotation = TextAnnotation("tag", "annotation")
        )
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment