How to set the part of the text view is clickable

后端 未结 20 994
无人共我
无人共我 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:19

    Created elegant Kotlin way with extension:

    fun TextView.setClickableText(text: Spanned,
                                  clickableText: String,
                                  @ColorInt clickableColor: Int,
                                  clickListener: () -> Unit) {
        val spannableString = SpannableString(text)
    
        val startingPosition: Int = text.indexOf(clickableText)
    
        if (startingPosition > -1) {
            val clickableSpan: ClickableSpan = object : ClickableSpan() {
                override fun onClick(textView: View) {
                    clickListener()
                }
    
                override fun updateDrawState(textPaint: TextPaint) {
                    super.updateDrawState(textPaint)
                    textPaint.isUnderlineText = false
                }
            }
    
            val endingPosition: Int = startingPosition + clickableText.length
            spannableString.setSpan(clickableSpan, startingPosition,
                    endingPosition, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            spannableString.setSpan(ForegroundColorSpan(clickableColor), startingPosition,
                    endingPosition, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            movementMethod = LinkMovementMethod.getInstance()
            highlightColor = Color.TRANSPARENT
        }
    
        setText(spannableString)
    }
    

提交回复
热议问题