Skip to content

Instantly share code, notes, and snippets.

@thenishchalraj
Last active January 21, 2021 07:02
Show Gist options
  • Save thenishchalraj/aed65c55e88ab373bb1016dd922b7bc9 to your computer and use it in GitHub Desktop.
Save thenishchalraj/aed65c55e88ab373bb1016dd922b7bc9 to your computer and use it in GitHub Desktop.
Code snippet for the sample of parsing long dynamic text into clickable links, if any available, using Spannable and Matcher with Kotlin in Android
private val urlPattern: Pattern = Pattern.compile(
"(?:^|[\\W])((ht|f)tp(s?):\\/\\/|www\\.)"
+ "(([\\w\\-]+\\.){1,}?([\\w\\-.~]+\\/?)*"
+ "[\\p{Alnum}.,%_=?&#\\-+()\\[\\]\\*$~@!:/{};']*)",
Pattern.CASE_INSENSITIVE or Pattern.MULTILINE or Pattern.DOTALL
)
private fun clickableLink{
try {
val str = SpannableString(longText)
val matcher = urlPattern.matcher(longText)
var matchStart: Int
var matchEnd: Int
while (matcher.find()){
matchStart = matcher.start(1)
matchEnd = matcher.end()
var url = longText.substring(matchStart, matchEnd)
if (!url.startsWith("http://") && !url.startsWith("https://"))
url = "https://$url"
val clickableSpan: ClickableSpan = object : ClickableSpan() {
override fun onClick(widget: View) {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
context?.startActivity(intent)
}
override fun updateDrawState(ds: TextPaint) {
super.updateDrawState(ds)
ds.isUnderlineText = false
}
}
str.setSpan(clickableSpan, matchStart, matchEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
mBinding.textViewLongText.text = str
mBinding.textViewLongText.movementMethod = LinkMovementMethod.getInstance()
}catch (e: Exception){
e.printStackTrace()
}
}
@thenishchalraj
Copy link
Author

The respective blog which explains the code above is here

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