Skip to content

Instantly share code, notes, and snippets.

@alexfu
Last active Mar 21, 2019
Embed
What would you like to do?
Making (Android) Spannable great again with Kotlin
val world = "World"
val mySpannedText = SpannableString("Hello ${world}!")
mySpannedText.spanWith(world) {
what = BackgroundColorSpan(Color.RED)
flags = Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
}
fun SpannableString.spanWith(target: String, apply: SpannableBuilder.() -> Unit) {
val builder = SpannableBuilder()
apply(builder)
val start = this.indexOf(target)
val end = start + target.length
setSpan(builder.what, start, end, builder.flags)
}
class SpannableBuilder {
lateinit var what: Any
var flags: Int = 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment