Kotlin-为SpannableStringBuilder创建自定义ext函数,在声明start、end和amp;时不使用重复参数;固定盘的flasg()
这是之前的MainActivity.ktKotlin-为SpannableStringBuilder创建自定义ext函数,在声明start、end和amp;时不使用重复参数;固定盘的flasg(),kotlin,code-duplication,kotlin-extension,spannablestringbuilder,Kotlin,Code Duplication,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.S
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) }
因此,我们不必使用重复的start、end和flags参数,而是打开进行修改,例如:
"string".putSpans(start, end, flags) { // for default value
span(ForgroundColorSpan(color), diffStart, diffEnd),
span(StyleSpan(BOLD), diffFlags)
}
您可以使用
core ktx
中包含的扩展,更具体地说,它简化了在kotlin中构建span-string
的过程,如下所示:
buildSpannedString {
bold {
append("hitherejoe")
}
}
我想你会这样使用它:
buildSpannedString {
bold {
inSpans(ForegroundColorSpan(ContextCompat.getColor(textView.context, R.color.mainGreen))) {
append("string")
}
}
}
参考请参见包装
我以Joe Birch的Medium post为例。您可以使用
核心ktx
中包含的扩展,更具体地说,它简化了kotlin中的跨距字符串的构建,因此:
buildSpannedString {
bold {
append("hitherejoe")
}
}
我想你会这样使用它:
buildSpannedString {
bold {
inSpans(ForegroundColorSpan(ContextCompat.getColor(textView.context, R.color.mainGreen))) {
append("string")
}
}
}
参考请参见包装
我从Joe Birch的Medium post中选取了这个例子。谢谢@maroš-Šeleng的回答,我真的很感激!今晚我要试试。谢谢你的回答@maroš-Šeleng,我真的很感激!今晚我要试试。