Created
February 3, 2020 07:06
-
-
Save dforest/e3c82cb7cbda1d19b39e4d5c1151d2c5 to your computer and use it in GitHub Desktop.
Add linked spannable to TextView for Kotlin Android.
This file contains 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
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