Created
January 27, 2022 17:57
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample usage