How to set the part of the text view is clickable

后端 未结 20 1449
无人共我
无人共我 2020-11-22 01:29

I have the text \"Android is a Software stack\". In this text i want to set the \"stack\" text is clickable. in the sense if you click on t

20条回答
  •  我寻月下人不归
    2020-11-22 02:11

    Complicated but universal solution on Kotlin

      /*
        * Receive Pair of Text and Action and set it clickable and appearing as link
        * */
    fun TextView.setClickableText(vararg textToSpanAndClickAction: Pair Unit>) {
        val builder = SpannableStringBuilder(text.toString())
    
        textToSpanAndClickAction.forEach { argPair ->
        val clickableSpan = object : ClickableSpan() {
            override fun onClick(widget: View) {
                argPair.second.invoke(argPair.first)
            }
        }
    
        this.text.toString().let { fullText ->
            val indexOfFirst = fullText.indexOf(argPair.first)
            val indexOfLast = indexOfFirst + argPair.first.length
            if (indexOfFirst < 0){
                //No match found
                return
            }else{
                builder.setSpan(
                    clickableSpan,
                    indexOfFirst,
                    indexOfLast,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                )
            }
        }
    }
    
    this.text = builder
        this.movementMethod = LinkMovementMethod.getInstance()
    }
    

    kotlin spannable

提交回复
热议问题