Skip to content

Instantly share code, notes, and snippets.

@vovahost
Created November 19, 2022 18:18
Show Gist options
  • Save vovahost/b1444227632ab9b4427497490a2e92ab to your computer and use it in GitHub Desktop.
Save vovahost/b1444227632ab9b4427497490a2e92ab to your computer and use it in GitHub Desktop.
Clickable Compose Text made simple
@Composable
fun AnnotatedClickableText() {
val termsUrl = "https://example.com/terms"
val privacyUrl = "https://example.com/privacy"
val annotatedText = buildAnnotatedString {
append("You agree to our ")
withStyle(style = SpanStyle(color = Color.Blue, fontWeight = FontWeight.Bold)) {
appendLink("Terms of Use", termsUrl)
}
append(" and ")
withStyle(style = SpanStyle(color = Color.Blue, fontWeight = FontWeight.Bold)) {
appendLink("Privacy Policy", privacyUrl)
}
}
ClickableText(
text = annotatedText,
onClick = { offset ->
annotatedText.onLinkClick(offset) { link ->
println("Clicked URL: $link")
// Open link in WebView.
}
}
)
}
fun AnnotatedString.Builder.appendLink(linkText: String, linkUrl: String) {
pushStringAnnotation(tag = linkUrl, annotation = linkUrl)
append(linkText)
pop()
}
fun AnnotatedString.onLinkClick(offset: Int, onClick: (String) -> Unit) {
getStringAnnotations(start = offset, end = offset).firstOrNull()?.let {
onClick(it.item)
}
}
@vovahost
Copy link
Author

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