Created
November 19, 2022 18:18
-
-
Save vovahost/b1444227632ab9b4427497490a2e92ab to your computer and use it in GitHub Desktop.
Clickable Compose Text made simple
This file contains hidden or 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
@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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See preview here https://stackoverflow.com/a/74502484/1502079