Skip to content

Instantly share code, notes, and snippets.

@happysingh23828
Last active October 13, 2022 12:26
Show Gist options
  • Save happysingh23828/6ccf5f4e5e02a90563ea4a0c2a4c5769 to your computer and use it in GitHub Desktop.
Save happysingh23828/6ccf5f4e5e02a90563ea4a0c2a4c5769 to your computer and use it in GitHub Desktop.
Find hypertext link in textview and get Callback when user clicks on it.
/**
* Enables click support for a TextView from a [fullText] String, which one containing one or multiple URLs.
* The [callback] will be called when a click is triggered.
*/
fun MaterialTextView.setTextWithLinkSupport(
fullText: Spannable,
callback: (String) -> Unit
) {
val spannable = SpannableString(fullText)
val matcher = Patterns.WEB_URL.matcher(spannable)
while (matcher.find()) {
val url = spannable.toString().substring(matcher.start(), matcher.end())
val urlSpan = object : URLSpan(fullText.toString()) {
override fun onClick(widget: View) {
callback(url)
}
}
spannable.setSpan(urlSpan, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
text = spannable
movementMethod = LinkMovementMethod.getInstance() // Make link clickable
}
/*
finds and colors all urls contained in a string
@param linkColor color for the url default is blue
@param linkClickAction action to perform when user click that link
*/
fun String.linkify(linkColor:Int = Color.BLUE,linkClickAction:((link:String) -> Unit)? = null): SpannableStringBuilder {
val builder = SpannableStringBuilder(this)
val matcher = Patterns.WEB_URL.matcher(this)
while(matcher.find()){
val start = matcher.start()
val end = matcher.end()
builder.setSpan(ForegroundColorSpan(Color.BLUE),start,end,0)
val onClick = object : ClickableSpan(){
override fun onClick(p0: View) {
linkClickAction?.invoke(matcher.group())
}
}
//builder.setSpan(onClick,start,end,0)
}
return builder
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment