Combining Spannable with String.format()

前端 未结 5 479
刺人心
刺人心 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 10:06

    I needed to replace %s placeholders in a String by a set of Spannables, and didn't find anything satisfying enough, so I implemented my own formatter as a kotlin String extension. Hopes it helps anyone.

    fun String.formatSpannable(vararg spans: CharSequence?): Spannable {
        val result = SpannableStringBuilder()
        when {
            spans.size != this.split("%s").size - 1 ->
                Log.e("formatSpannable",
                        "cannot format '$this' with ${spans.size} arguments")
            !this.contains("%s") -> result.append(this)
            else -> {
                var str = this
                var spanIndex = 0
                while (str.contains("%s")) {
                    val preStr = str.substring(0, str.indexOf("%s"))
                    result.append(preStr)
                    result.append(spans[spanIndex] ?: "")
                    str = str.substring(str.indexOf("%s") + 2)
                    spanIndex++
                }
                if (str.isNotEmpty()) {
                    result.append(str)
                }
            }
        }
        return result
    }
    

    and then usage as follows

    "hello %s kotlin %s world".formatSpannable(span0, span1)
    

提交回复
热议问题