-
-
Save hector6872/e520964eefd5da33e127b36554c32be8 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 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 | |
} |
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 | |
): 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