简体   繁体   English

Android - Spannable:无法一次设置多个跨度

[英]Android - Spannable: Unable to set multiple spans at once

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.但是"my full length of the string"之后的所有内容都会着色。 Could someone please help figure out what is wrong with the above method?有人可以帮忙找出上述方法有什么问题吗?

thanks谢谢

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
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM