Last active
May 12, 2023 10:33
-
-
Save micHar/99d8da443bfb9fc2e92a61ebaaacba72 to your computer and use it in GitHub Desktop.
Helper function loading annotated strings from strings.xml (might require further optimization)
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 android.text.Annotation | |
import android.text.SpannedString | |
import androidx.annotation.StringRes | |
import androidx.compose.runtime.Composable | |
import androidx.compose.ui.platform.LocalContext | |
import androidx.compose.ui.text.AnnotatedString | |
import androidx.compose.ui.text.SpanStyle | |
import androidx.core.text.getSpans | |
@Composable | |
fun annotatedStringResource( | |
@StringRes id: Int, | |
spanStyles: (Annotation) -> SpanStyle? = { null } | |
): AnnotatedString { | |
val resources = LocalContext.current.resources | |
val spannedString = SpannedString(resources.getText(id)) | |
val resultBuilder = AnnotatedString.Builder() | |
resultBuilder.append(spannedString.toString()) | |
spannedString.getSpans<Annotation>(0, spannedString.length).forEach { annotation -> | |
val spanStart = spannedString.getSpanStart(annotation) | |
val spanEnd = spannedString.getSpanEnd(annotation) | |
resultBuilder.addStringAnnotation( | |
tag = annotation.key, | |
annotation = annotation.value, | |
start = spanStart, | |
end = spanEnd | |
) | |
spanStyles(annotation)?.let { resultBuilder.addStyle(it, spanStart, spanEnd) } | |
} | |
return resultBuilder.toAnnotatedString() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage:
spanStyle
sets up optional styling based on annotation.And AnnotatedString.getStringAnnotations are implicitly provided to e.g. provide clickable behavior.