这是之前的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
到目前为止,这是我的方法 .
Extension.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) }
所以我们不必使用重复的start,end和flags参数,而是打开修改,例如:
"string".putSpans(start, end, flags) { // for default value
span(ForgroundColorSpan(color), diffStart, diffEnd),
span(StyleSpan(BOLD), diffFlags)
}
1 回答
您可以使用
core-ktx
中包含的扩展来简化使用,更具体地说,在kotlin中构建SpannedString
,如下所示:我想你会像这样使用它:
请参阅androidx.text包以供参考 .
我从Joe Birch的this Medium帖子中拿了这个例子 .