androidkotlintextviewspannablestring

Kotlin -How to Change Text Color of a SpannableString with an Image


I have a string with an image on the back. I'm able to change the image color to green but I can't get the text color to change to green also. It stays black.

enter image description here

"abc is available" should be green too

val span = SpannableStringBuilder()
span.append("abc is available")
span.setSpan(R.color.myGreenColor, 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, ContextCompat.getColor(this, R.color.myGreenColor))

    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
}

Solution

  • The setSpan() method shouldn't take a color resource at the first parameter, it accepts it as it's of type Object; but it won't have any affection.

    setSpan() should take an object that implements ParcelableSpan.

    span.setSpan(R.color.myGreenColor, 0, span.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)

    So, this line of code won't have any affect; instead you'd replace it with ForegroundColorSpan:

    span.setSpan(ForegroundColorSpan(ResourcesCompat.getColor(resources, R.color.myGreenColor, null)),
                0, span.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)