textView查找关键字并设置跳转链接
2022-01-27 本文已影响0人
songsyl1207
直接上代码
fun createLink(text: String, textView: TextView, targetStr: String = "《隐私协议》") {
val list = text.findIndexSet(targetStr)
val spannableString = SpannableString(text)
val targetLength = targetStr.length
list.forEach {
val clickSpan = object : ClickableSpan() {
override fun onClick(widget: View) {
with(widget.context) {
startActivity(Intent(this, AgreementActivity::class.java))
}
}
override fun updateDrawState(ds: TextPaint) {
super.updateDrawState(ds)
// ds.isUnderlineText = false
ds.isFakeBoldText = true
ds.color = Color.parseColor("#00b2ca")
}
}
spannableString.setSpan(
clickSpan, it, it + targetLength,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
textView.text = spannableString
textView.movementMethod = LinkMovementMethod.getInstance()
}
注意:
1、clickSpan不能提取到for循环外,否则只有最后一个匹配项生效
2、textView.movementMethod = LinkMovementMethod.getInstance() 必须设置,否则点击不生效
查找关键字方法
fun String.findIndexSet(target: String): List<Int> {
val match = Pattern.compile(target).matcher(this)
val list = mutableListOf<Int>()
while (match.find()) {
list.add(match.start())
}
return list
}