应用多个ForegroundColorSpan

时间:2019-02-09 11:35:21

标签: android kotlin spannablestring

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

但是,只有最后一次应用的跨度才生效。

我的代码是:

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

1 个答案:

答案 0 :(得分:1)

每次您都需要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
}