应用多个 ForegroundColorSpan

Applying multiple ForegroundColorSpan

我想将 ForegroundColorSpan 应用于给定字符串中的多个单词。

但是,只有上次应用的 span 生效。

我的代码是:

private fun formatString(target: String, vararg formattableWords: String): SpannableString {
    val spannableString = SpannableString(target)

    val colorSpan = ForegroundColorSpan(ContextCompat.getColor(context!!, R.color.colorPrimary))

    formattableWords.forEach { formattableWord ->
        val start = target.indexOf(formattableWord, ignoreCase = true)
        val end = start + formattableWord.length

        spannableString.setSpan(colorSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
    }

    return spannableString
}

当我在下面的代码中调用它时:

entryTermsConditionsPrivacy.text = formatString(
            "By using APP you agree to the Terms and Conditions and the Privacy Policy.",
            "APP", "Terms and Conditions", "Privacy Policy"
        )

只有Privacy Policy收到申请ForegroundColorSpan

每次你都需要 ForegroundColorSpan

的新对象
private fun formatString(target: String, vararg formattableWords: String): SpannableString {
val spannableString = SpannableString(target)

//    val colorSpan = ForegroundColorSpan(ContextCompat.getColor(this, R.color.colorPrimary))

formattableWords.forEach { formattableWord ->
  val start = target.indexOf(formattableWord, ignoreCase = true)
  val end = start + formattableWord.length

  spannableString.setSpan(ForegroundColorSpan(ContextCompat.getColor(this, R.color.colorPrimary)), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
}

return spannableString
}