这是之前的 MainActivity.kt
var spannable = SpannableStringBuilder("$noColorText$coloredText")
spannable.setSpan(
ForegroundColorSpan(ContextCompat.getColor(textView.context, R.color.mainGreen)),
noColorText.length, spannable.length,
Spannable.SPAN_EXCLUSIVE_INCLUSIVE
)
spannable.setSpan(
StyleSpan(BOLD),
noColorText.length, spannable.length,
Spannable.SPAN_EXCLUSIVE_INCLUSIVE
)
textView.text = spannable
到目前为止,这是我的方法。
扩展名.kt
// TODO: e.g: "string".putSpans(start, end, flags) { ForgroundColorSpan(color), StyleSpan(BOLD) }
fun String.putSpans(vararg flags: Int.() -> Unit, spanBuilder: SpannableStringBuilder.() -> Unit):
SpannableStringBuilder = SpannableStringBuilder(this).apply(spanBuilder)
MainActivity.kt
// TODO: Change SpannableBuilder to be modular (without, reinput duplicate args)
val resultSpan = "$noColorText$coloredText ".putSpans {
setSpan(ForegroundColorSpan(ContextCompat.getColor(textView.context, R.color.mainGreen)),
noColorText.length, this.length, // this is duplicate
Spannable.SPAN_EXCLUSIVE_INCLUSIVE) // this is duplicate
setSpan(StyleSpan(BOLD),
noColorText.length, this.length, // this is duplicate
Spannable.SPAN_EXCLUSIVE_INCLUSIVE) // this is duplicate
}
textView.text = resultSpan
这是否可以创建这样的扩展
"string".putSpans(start, end, flags) { ForgroundColorSpan(color), StyleSpan(BOLD) }
所以我们不必使用重复的开始、结束和标志参数,但可以修改,例如:
"string".putSpans(start, end, flags) { // for default value
span(ForgroundColorSpan(color), diffStart, diffEnd),
span(StyleSpan(BOLD), diffFlags)
}
最佳答案
您可以使用 core-ktx
中包含的扩展名它简化了使用,更具体地说,构建 SpannedString
在 kotlin 中是这样的:
buildSpannedString {
bold {
append("hitherejoe")
}
}
我猜你会这样使用它:
buildSpannedString {
bold {
inSpans(ForegroundColorSpan(ContextCompat.getColor(textView.context, R.color.mainGreen))) {
append("string")
}
}
}
见 androidx.text包供引用。
我以 this 中的示例为例乔·伯奇(Joe Birch)的中等帖子。
关于Kotlin - 在为 setSpans() 声明开始、结束和标志时,为 SpannableStringBuilder 创建没有重复参数的自定义 ext 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53705717/