首页 > 解决方案 > 使用 String.format() 时更改字符串两部分的颜色

问题描述

我正在使用以下内容来显示文字游戏应用程序中的剩余时间。

remainingTime.setText(String.format(Locale.getDefault(),"REMAINING TIME: %d MNS %d SECONDS ",(millisUntilFinished / 1000) / 60 ,(millisUntilFinished / 1000) % 60));

我想更改分钟和第二个文本的颜色。如何在占位符中定义颜色?

我希望它看起来像这样: 在此处输入图像描述

标签: androidstring.format

解决方案


如果您使用的是 Kotlin,则可以使用扩展函数来完成。

    fun TextView.setColouredSpan(word: String, color: Int) {
        val spannableString = SpannableString(text)
        val start = text.indexOf(word)
        val end = text.indexOf(word) + word.length
        try {
            spannableString.setSpan(ForegroundColorSpan(color), start, end,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            text = spannableString
        } catch (e: IndexOutOfBoundsException) {
         println("'$word' was not not found in TextView text")
    }
}

像这样将文本设置为 TextView 后使用它

private val blueberry by lazy { getColor(R.color.blueberry) }

textViewTip.setColouredSpan("Warning", blueberry)

推荐阅读