Last active
March 21, 2019 14:50
-
-
Save alexfu/957b31faaa419cfe6cf706f7a6d3e0fe to your computer and use it in GitHub Desktop.
Making (Android) Spannable great again with Kotlin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
val world = "World" | |
val mySpannedText = SpannableString("Hello ${world}!") | |
mySpannedText.spanWith(world) { | |
what = BackgroundColorSpan(Color.RED) | |
flags = Spanned.SPAN_EXCLUSIVE_EXCLUSIVE | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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