0

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

4

1 回答 1

0

上面的代码很好。问题是我试图在一个带颜色的跨度上设置可点击跨度。并且可点击的跨度会覆盖其他颜色。设置方法如下:

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
    }
于 2020-03-28T12:58:08.197 回答