You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin:如何修改带图片的SpannableString的文字颜色

问题解决:SpannableString文本颜色不生效

你的问题出在给文本设置颜色的方式上——直接把R.color.myGreenColor这个资源ID传给setSpan()是没用的,setSpan()需要传入具体的Span对象,而不是整数ID。要修改文本颜色,得用ForegroundColorSpan来包裹实际的颜色值。

修改后的代码如下:

val span = SpannableStringBuilder()
span.append("abc is available")
// 替换原来的setSpan,用ForegroundColorSpan包裹颜色值
val greenColor = ContextCompat.getColor(this, R.color.myGreenColor)
span.setSpan(ForegroundColorSpan(greenColor), 0, span.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
span.append("  ")

val unwrappedDrawable = AppCompatResources.getDrawable(this, R.drawable.checkmark_icon)?.mutate()
if (unwrappedDrawable != null) {
    val wrappedDrawable = DrawableCompat.wrap(unwrappedDrawable)
    DrawableCompat.setTint(wrappedDrawable, greenColor)

    val lineHeight = binding.myTextView.lineHeight
    wrappedDrawable.setBounds(0, 0, lineHeight, lineHeight)

    val image = ImageSpan(wrappedDrawable, 0)
    span.setSpan(image, span.length -1, span.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)

    binding.myTextView.text = span
}

这里先通过ContextCompat.getColor()拿到实际的颜色值,再用ForegroundColorSpan把颜色包装成Span对象传给setSpan(),这样文本就能正常显示绿色了。图片的 tint 处理逻辑是正确的,不需要改动。

内容的提问来源于stack exchange,提问作者Lance Samaria

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 06:34:55