Kotlin - 为setSpans()声明start,end和flasg时,为SpannableStringBuilder创建自定义ext函数,不带重复参数

loading...


0

这是之前的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) 
}

loading...

1回答

  • 1

    您可以使用 core-ktx 中包含的扩展来简化使用,更具体地说,在kotlin中构建 SpannedString ,如下所示:

    buildSpannedString {
        bold {
            append("hitherejoe")
        }
    }
    

    我想你会像这样使用它:

    buildSpannedString {
        bold {
            inSpans(ForegroundColorSpan(ContextCompat.getColor(textView.context, R.color.mainGreen))) {
                append("string")
            }
        }
    }
    

    请参阅androidx.text包以供参考 .

    我从Joe Birch的this Medium帖子中拿了这个例子 .

评论

暂时没有评论!