android - 使用 String.format() 时更改字符串两部分的颜色
问题描述
我正在使用以下内容来显示文字游戏应用程序中的剩余时间。
remainingTime.setText(String.format(Locale.getDefault(),"REMAINING TIME: %d MNS %d SECONDS ",(millisUntilFinished / 1000) / 60 ,(millisUntilFinished / 1000) % 60));
我想更改分钟和第二个文本的颜色。如何在占位符中定义颜色?
解决方案
如果您使用的是 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)
推荐阅读
- config - rasa 的小鸭模块
- php - 从我的网络服务器上的文件夹下载 zip 文件
- c# - Roslyn 中的 INamedTypeSymbol 继承关系
- c# - 如何使用 Refit 反序列化数组?
- blockchain - Composer Playground 无法加载示例业务网络
- function - TypeScript:函数表达式重载
- database - 使用多个可选参数在 H2 数据库中实现搜索查询
- android - Stripe PaymentMethodsActivity 添加谷歌支付按钮
- php - For 循环仅显示最终结果
- java - 模拟 BouncyCastle 类 - SecurityException