Skip to content

Instantly share code, notes, and snippets.

Forked from radoyankov/Example.kt
Last active Aug 18, 2021
What would you like to do?
Easy Spannable on Kotlin
val spanned = spannable{ bold("some") + italic(" formatted") + color(Color.RED, " text") }
val nested = spannable { italic(underline(bold(size(2f, color(Color.RED, "Red Bold Color"))))) }
val noWrapping = bold("no ") + sub("wrapping ) + sup("also ") + "works"
text_view.text = spanned + nested + noWrapping
import android.text.Spannable
import android.text.SpannableString
import android.text.TextUtils
fun spannable(func: () -> SpannableString) = func()
private fun span(s: CharSequence, o: Any) =
(if (s is String) SpannableString(s) else s as? SpannableString
?: SpannableString("")).apply { setSpan(o, 0, length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) }
operator fun SpannableString) = SpannableString(TextUtils.concat(this, s))
operator fun String) = SpannableString(TextUtils.concat(this, s))
fun bold(s: CharSequence) = span(s, StyleSpan(
fun bold(s: SpannableString) = span(s, StyleSpan(
fun italic(s: CharSequence) = span(s, StyleSpan(
fun italic(s: SpannableString) = span(s, StyleSpan(
fun underline(s: CharSequence) = span(s, UnderlineSpan())
fun underline(s: SpannableString) = span(s, UnderlineSpan())
fun strike(s: CharSequence) = span(s, StrikethroughSpan())
fun strike(s: SpannableString) = span(s, StrikethroughSpan())
fun sup(s: CharSequence) = span(s, SuperscriptSpan())
fun sup(s: SpannableString) = span(s, SuperscriptSpan())
fun sub(s: CharSequence) = span(s, SubscriptSpan())
fun sub(s: SpannableString) = span(s, SubscriptSpan())
fun size(size: Float, s: CharSequence) = span(s, RelativeSizeSpan(size))
fun size(size: Float, s: SpannableString) = span(s, RelativeSizeSpan(size))
fun color(color: Int, s: CharSequence) = span(s, ForegroundColorSpan(color))
fun color(color: Int, s: SpannableString) = span(s, ForegroundColorSpan(color))
fun background(color: Int, s: CharSequence) = span(s, BackgroundColorSpan(color))
fun background(color: Int, s: SpannableString) = span(s, BackgroundColorSpan(color))
fun url(url: String, s: CharSequence) = span(s, URLSpan(url))
fun url(url: String, s: SpannableString) = span(s, URLSpan(url))
fun normal(s: CharSequence) = span(s, SpannableString(s))
fun normal(s: SpannableString) = span(s, SpannableString(s))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment