Android - Spannable: Unable to set multiple spans at once

281 views Asked by At

I have the following code to set a color span on multiple subStrings of the same string.

fun getColoredText(text: String, @ColorInt color: Int, vararg coloredSubText: String): Spannable {

        val spannable = SpannableString(text)

        for (textToColor in coloredSubText) {

            val start = text.indexOf(textToColor)

            spannable.setSpan(
                ForegroundColorSpan(color),
                start,
                start + textToColor.length - 1,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            spannable.

        }

        return spannable
    }

I provide the following arguments:

getColoredText("This is my full length of the string", someColorValue, "my", "length")

But everything after "my full length of the string" gets colored. Could someone please help figure out what is wrong with the above method?

thanks

1

There are 1 answers

0
Sunny On

The above code is fine. The issue was that i was trying to set clickable span on a spannable with color. And the clickable span overrides the other colors. The way to set it as follows:

fun getClickableTextWithColor(spannable: Spannable, clickableText: String, @ColorInt color: Int, onClickListener: (View) -> Unit): Spannable {
        val text = spannable.toString()

        val start = text.indexOf(clickableText)
        spannable.setSpan(
            object : ClickableSpan() {
                override fun onClick(widget: View) {
                    onClickListener.invoke(widget)
                }

                override fun updateDrawState(ds: TextPaint) {
                    super.updateDrawState(ds)
                    ds.color = color
                }
            },
            start,
            start + clickableText.length,
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        return spannable
    }