Set color of TextView span in Android

前端 未结 15 1676
眼角桃花
眼角桃花 2020-11-22 05:54

Is it possible to set the color of just span of text in a TextView?

I would like to do something similar to the Twitter app, in which a part of the text is blue. See

15条回答
  •  野性不改
    2020-11-22 06:22

    Here's a Kotlin Extension Function I have for this

        fun TextView.setColouredSpan(word: String, color: Int) {
            val spannableString = SpannableString(text)
            val start = text.indexOf(word)
            val end = text.indexOf(word) + word.length
            try {
                spannableString.setSpan(ForegroundColorSpan(color), start, end,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
                text = spannableString
            } catch (e: IndexOutOfBoundsException) {
             println("'$word' was not not found in TextView text")
        }
    }
    

    Use it after you have set your text to the TextView like so

    private val blueberry by lazy { getColor(R.color.blueberry) }
    
    textViewTip.setColouredSpan("Warning", blueberry)
    

提交回复
热议问题