I just wrote a short and simple function which can automatically detect links/hyperlinks in your text/string and convert them into clickable links/hyperlinks.
It uses the newly introduced LinkAnnotation (unlike the deprecated ClickableText).
The regex matches all the possible combinations of a valid URL format.
fun linkifiedText(str: String): AnnotatedString {
val urlRegex = Regex("\\b((https?://)?([a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,}(:\\d+)?(/\\S*)?)\\b")
val matches = urlRegex.findAll(str).map { it.range }
var lastIntRangeIndex = 0
return buildAnnotatedString {
matches.forEach { intRange ->
append(str.slice(IntRange(0, intRange.first - 1)))
withLink(
LinkAnnotation.Url(
if (str.slice(intRange)
.startsWith("www")
) "https://" + str.slice(intRange) else str.slice(intRange),
TextLinkStyles(
style = SpanStyle(
color = Color.Blue,
textDecoration = TextDecoration.Underline
)
)
)
) {
append(str.slice(intRange))
}
lastIntRangeIndex = intRange.last + 1
}
append(str.slice(IntRange(lastIntRangeIndex, str.length - 1)))
}
}
The usage is pretty simple
Text(text = linkifiedText("your_text"))
Any optimization suggestions are appreciated