gpt4 book ai didi

android - 应用多个 ForegroundColorSpan

转载 作者:行者123 更新时间:2023-11-29 23:19:36 32 4
gpt4 key购买 nike

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

关于android - 应用多个 ForegroundColorSpan,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54605814/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com