moc*_*dwi 1 code-duplication kotlin kotlin-extension spannablestringbuilder
这是之前的 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
Run Code Online (Sandbox Code Playgroud)
到目前为止,这是我的方法。
扩展名.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)
Run Code Online (Sandbox Code Playgroud)
主活动.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
Run Code Online (Sandbox Code Playgroud)
是否可以像这样创建扩展
"string".putSpans(start, end, flags) { ForgroundColorSpan(color), StyleSpan(BOLD) }
Run Code Online (Sandbox Code Playgroud)
所以我们不必使用重复的开始,结束,也标志参数,但可以修改,例如:
"string".putSpans(start, end, flags) { // for default value
span(ForgroundColorSpan(color), diffStart, diffEnd),
span(StyleSpan(BOLD), diffFlags)
}
Run Code Online (Sandbox Code Playgroud)
您可以使用其中包含的扩展core-ktx来简化使用,更具体地说,SpannedString在 kotlin 中构建,如下所示:
buildSpannedString {
bold {
append("hitherejoe")
}
}
Run Code Online (Sandbox Code Playgroud)
我猜你会像这样使用它:
buildSpannedString {
bold {
inSpans(ForegroundColorSpan(ContextCompat.getColor(textView.context, R.color.mainGreen))) {
append("string")
}
}
}
Run Code Online (Sandbox Code Playgroud)
请参阅androidx.text包以供参考。
我从Joe Birch 的这篇Medium 帖子中举了一个例子。
| 归档时间: |
|
| 查看次数: |
2508 次 |
| 最近记录: |