Skip to content

Instantly share code, notes, and snippets.

@hrules6872
Forked from alexfu/Demo.kt
Last active January 25, 2019 20:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hrules6872/e520964eefd5da33e127b36554c32be8 to your computer and use it in GitHub Desktop.
Save hrules6872/e520964eefd5da33e127b36554c32be8 to your computer and use it in GitHub Desktop.
Making (Android) Spannable great again with Kotlin
val world = "World"
val spannedText = SpannableString("Hello $world!")
spannedText
.spanWith(world) {
what = BackgroundColorSpan(Color.RED)
flags = Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
}
.spanWith(world) {
what = StyleSpan(Typeface.BOLD)
flags = Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
}
fun SpannableString.spanWith(
target: String,
apply: SpannableBuilder.() -> Unit
): SpannableString {
val builder = SpannableBuilder()
apply(builder)
val start = this.indexOf(target)
val end = start + target.length
setSpan(builder.what, start, end, builder.flags)
return this
}
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