安卓改变TextView中部分文字颜色

效果图

实现方案

  1. 方案1: 通过html方式
private fun setTextByHtml() {
        val str = "默认颜色<font color='#FF0000'>红颜色</font>"
        textView1.text = Html.fromHtml(str)
    }
  1. 方案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

发布了407 篇原创文章 · 获赞 90 · 访问量 39万+

猜你喜欢

转载自blog.csdn.net/yinxing2008/article/details/103617463