我想将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
答案 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
}