Android: ClickableSpan in clickable TextView

后端 未结 7 1718
借酒劲吻你
借酒劲吻你 2020-11-27 02:53

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

相关标签:
7条回答
  • 2020-11-27 03:24

    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")
        }
    
    0 讨论(0)
提交回复
热议问题