I have a textview that can contain clickable links. When one of this links is clicked, I want to start an activity. This works fine, but it should also be possible to click
copy below function
private fun setClickableHighLightedText(
tv: TextView,
textToHighlight: String,
onClickListener: View.OnClickListener?
) {
val tvt = tv.text.toString()
var ofe = tvt.indexOf(textToHighlight, 0)
val clickableSpan = object : ClickableSpan() {
override fun onClick(textView: View) {
onClickListener?.onClick(textView)
}
override fun updateDrawState(ds: TextPaint) {
super.updateDrawState(ds)
//set color of the text
ds.color = getColor(R.color.black)
//draw underline base on true/false
ds.isUnderlineText = false
}
}
val wordToSpan = SpannableString(tv.text)
var ofs = 0
while (ofs < tvt.length && ofe != -1) {
ofe = tvt.indexOf(textToHighlight, ofs)
if (ofe == -1)
break
else {
wordToSpan.setSpan(
clickableSpan,
ofe,
ofe + textToHighlight.length,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
)
tv.setText(wordToSpan, TextView.BufferType.SPANNABLE)
tv.movementMethod = LinkMovementMethod.getInstance()
}
ofs = ofe + 1
}
}
use above function and pass textview,clickble string
setClickableHighLightedText(tvTest,"test") {
showMessage("click")
}