Skip to content

Instantly share code, notes, and snippets.

@toantran-ea
Created September 19, 2020 04:49
Show Gist options
  • Save toantran-ea/338ffcaa4868529c098c099f1572411f to your computer and use it in GitHub Desktop.
Save toantran-ea/338ffcaa4868529c098c099f1572411f to your computer and use it in GitHub Desktop.
Effortless SpannableStringBuilder
package mobi.toan.etc
import android.text.SpannableStringBuilder
import android.text.Spanned.SPAN_INCLUSIVE_EXCLUSIVE
import java.util.*
/**
Kotlin's version of Thuss from Jake Wharton
**/
class AweSpanBuilder {
private val spannableBuilder = SpannableStringBuilder()
private val stack: Deque<Span> = ArrayDeque()
fun append(string: String): AweSpanBuilder {
spannableBuilder.append(string)
return this
}
fun append(string: CharSequence): AweSpanBuilder {
spannableBuilder.append(string)
return this
}
fun append(string: Char): AweSpanBuilder {
spannableBuilder.append(string)
return this
}
fun append(string: Int): AweSpanBuilder {
spannableBuilder.append(string.toString())
return this
}
fun pushSpan(span: Any): AweSpanBuilder {
stack.addLast(Span(spannableBuilder.length, span))
return this
}
fun popSpan(): AweSpanBuilder {
val span = stack.removeLast()
spannableBuilder.setSpan(span.span, span.start, spannableBuilder.length, SPAN_INCLUSIVE_EXCLUSIVE)
return this
}
fun build(): CharSequence {
while (!stack.isEmpty()) {
popSpan()
}
return spannableBuilder
}
inner class Span(val start: Int, val span: Any)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment