Kotlin - 在为 setSpans() 声明开始、结束和标志时,为 SpannableStringBuilder 创建没有重复参数的自定义 ext 函数

标签 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.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/

相关文章:

kotlin - 意外覆盖 : The following declarations have the same JVM signature

android - 如何在 Kotlin Android 中正确使用 URL

kotlin - 如何组织 Kotlin 扩展方法

android - LifecycleScope 和 SharedFlow 的组合是否消除了对 ViewModel 的需求?

android - Jetpack 撰写 : Textfield and FAB not using full width

kotlin - 如何在 Kotlin 协程中使用阻塞(I/O 绑定(bind))API?

c++ - 如何避免与大多数相同成员函数的代码重复?

c# - 如何简化 try-catch 的 return 语句

android - 在函数之间传递 MutableLiveData

sql-server-2008 - 如何避免只有一个参数不同的同一查询的重复?