Skip to content

Instantly share code, notes, and snippets.

@dforest
Created February 3, 2020 07:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dforest/e3c82cb7cbda1d19b39e4d5c1151d2c5 to your computer and use it in GitHub Desktop.
Save dforest/e3c82cb7cbda1d19b39e4d5c1151d2c5 to your computer and use it in GitHub Desktop.
Add linked spannable to TextView for Kotlin Android.
fun TextView.addLinkedSpannable(highlight: String, listener: (view: View) -> Unit) {
val original = when {
(text != null && text is SpannableString) -> text
else -> SpannableString(text)
}
val startPos = original.indexOf(highlight)
movementMethod = LinkMovementMethod.getInstance()
text = SpannableStringBuilder(original).also {
it.setSpan(object : ClickableSpan() {
override fun onClick(view: View) {
listener(view)
}
override fun updateDrawState(ds: TextPaint) {
super.updateDrawState(ds)
ds.color = ContextCompat.getColor(context, R.color.black)
}
}, startPos, startPos + highlight.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment