textView查找关键字并设置跳转链接

直接上代码

    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 {
    val match = Pattern.compile(target).matcher(this)
    val list = mutableListOf()
    while (match.find()) {
        list.add(match.start())
    }
    return list
}

你可能感兴趣的:(textView查找关键字并设置跳转链接)