Combining Spannable with String.format()

前端 未结 5 478
刺人心
刺人心 2021-01-31 09:28

Suppose you have the following string:

String s = \"The cold hand reaches for the %1$s %2$s Ellesse\'s\";
String old = \"old\"; 
String tan = \"tan\"; 
String fo         


        
5条回答
  •  长情又很酷
    2021-01-31 09:57

    I made simple Kotlin extension function that should solve String.format spanned issue:

    fun Context.getStringSpanned(@StringRes resId: Int, vararg formatArgs: Any): Spanned {
        var lastArgIndex = 0
        val spannableStringBuilder = SpannableStringBuilder(getString(resId, *formatArgs))
        for (arg in formatArgs) {
            val argString = arg.toString()
            lastArgIndex = spannableStringBuilder.indexOf(argString, lastArgIndex)
            if (lastArgIndex != -1) {
                (arg as? CharSequence)?.let {
                    spannableStringBuilder.replace(lastArgIndex, lastArgIndex + argString.length, it)
                }
                lastArgIndex += argString.length
            }
        }
    
        return spannableStringBuilder
    }
    

提交回复
热议问题