如何逐行更改 TextView 的颜色?

How to change color of a TextView line by line?

我有这样的文字:

我想更改每行的颜色(或字体粗细)以向用户显示进度。

你可以使用 SpannableString 来完成这个

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