You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为TextView中指定位置的重复动态文本设置蓝色?

解决TextView中特定位置重复字符串的着色问题

你当前代码里的indexOf只会返回目标字符串第一次出现的位置,所以只能给第一个"ABCD"上色。要给指定次数出现的字符串着色,关键是先精准定位到目标字符串第N次出现的起始索引。

1. 实现查找第N次出现的字符串索引工具方法

写一个遍历统计的工具函数,找到目标字符串第N次出现的起始位置:

fun findNthOccurrence(original: String, target: String, occurrence: Int): Int {
    var count = 0
    var startIndex = 0
    while (count < occurrence) {
        val index = original.indexOf(target, startIndex)
        if (index == -1) {
            // 找不到第N次出现,返回-1
            return -1
        }
        count++
        if (count == occurrence) {
            return index
        }
        // 从当前匹配位置的下一位继续查找
        startIndex = index + target.length
    }
    return -1
}

2. 调用工具方法完成着色

传入你需要的目标字符串和出现次数,定位后设置颜色Span,同时处理找不到的边界情况:

val title2 = "ABCD is a place where i live. ABCD is known for tourism"
val title3 = "ABCD"
val targetOccurrence = 2 // 要着色的是第2次出现的字符串

val spannableString = SpannableString(title2)
val startIndex = findNthOccurrence(title2, title3, targetOccurrence)

if (startIndex != -1) {
    val endIndex = startIndex + title3.length
    spannableString.setSpan(
        ForegroundColorSpan(Color.BLUE),
        startIndex,
        endIndex,
        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
    )
}

textview.text = spannableString

额外说明

  • 这个方案完全支持动态传入目标字符串和指定出现位置,适配你的业务需求。
  • 如果目标字符串实际出现次数小于指定的次数(比如要找第3次但只有2次),函数会返回-1,此时不会执行着色逻辑,避免数组越界崩溃。

内容的提问来源于stack exchange,提问作者Heleena Joy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 22:05:29