Search code examples
androidkotlinspannablestring

Applying multiple ForegroundColorSpan


I want to apply ForegroundColorSpan to multiple words in a given string.

However, only the last applied span is taking effect.

My code is:

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
}

When I call it in the following code:

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

Only Privacy Policy receives the applied ForegroundColorSpan


Solution

  • Every time you will need new object of 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
    }