我有以下代码来在同一字符串的多个子字符串上设置颜色范围。
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
}
我提供以下参数:
getColoredText("This is my full length of the string", someColorValue, "my", "length")
但是"my full length of the string"
之后的所有内容都会变色。有人可以帮忙弄清楚上述方法有什么问题吗?
谢谢
上面的代码很好。问题是我试图在可设置跨度的颜色上设置可点击跨度。可点击范围会覆盖其他颜色。设置方法如下:
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
}