效果图
实现方案
- 方案1: 通过html方式
private fun setTextByHtml() {
val str = "默认颜色<font color='#FF0000'>红颜色</font>"
textView1.text = Html.fromHtml(str)
}
- 方案2: 通过SpannableString设置
private fun setTextBySpannable() {
val spannableString = SpannableString("默认颜色红颜色")
val color = Color.parseColor("#FF0000")
val startIndex = 4
val endIndex = spannableString.length
spannableString.setSpan(
ForegroundColorSpan(color),
startIndex,
endIndex,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
)
textView2.text = spannableString
}
源代码
https://gitee.com/cxyzy1/colorTextView