-
-
Save captswag/7a6f077c2a0eea52e047fa275aeb67ec to your computer and use it in GitHub Desktop.
Rewrote Jake Wharton's wrapper of SpannableStringBuilder in Kotlin
This file contains 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
import android.text.SpannableStringBuilder | |
import android.text.Spanned.SPAN_INCLUSIVE_EXCLUSIVE | |
import java.util.ArrayDeque | |
import java.util.Deque | |
// https://gist.github.com/JakeWharton/11274467 | |
public class Truss { | |
private val builder: SpannableStringBuilder = SpannableStringBuilder() | |
private val stack: Deque<Span> = ArrayDeque() | |
fun append(string: String): Truss { | |
builder.append(string) | |
return this | |
} | |
fun append(charSequence: CharSequence): Truss { | |
builder.append(charSequence) | |
return this | |
} | |
fun append(char: Char): Truss { | |
builder.append(char) | |
return this | |
} | |
fun append(number: Int): Truss { | |
builder.append("$number") | |
return this | |
} | |
/** Starts {@code span} at the current position in the builder. */ | |
fun pushSpan(span: Any): Truss { | |
stack.addLast(Span(builder.length, span)) | |
return this | |
} | |
/** End the most recently pushed span at the current position in the builder. */ | |
fun popSpan(): Truss { | |
val span = stack.removeLast() | |
builder.setSpan(span.span, span.start, builder.length, SPAN_INCLUSIVE_EXCLUSIVE) | |
return this | |
} | |
/** Create the final {@link CharSequence}, popping any remaining spans. */ | |
fun build(): CharSequence { | |
while (!stack.isEmpty()) { | |
popSpan() | |
} | |
return builder | |
} | |
} | |
private data 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