Search code examples
androidkotlintextview

How to change color of a TextView line by line?


I have text that goes like that:

  • loading item 1
  • loading item 2
  • loading item 3

I want to change color (or fontWeight) of every line to show user the progress.


Solution

  • You can use SpannableString for this

    val currentText = textView.text
    val spannable = SpannableString(currentText)
    spannable.setSpan(ForegroundColorSpan(Color.RED), 0, endOfFirstLine, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
    spannable.setSpan(ForegroundColorSpan(Color.GREEN), endOfFirstLine, endOfSecondLine, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
    spannable.setSpan(ForegroundColorSpan(Color.YELLOW), endOfSecondLine, endOfThirdLine, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
    
    // Set the colored text
    textView.text = spannable