-
-
Save twalk4821/39e1c8914a3919fe4bdc1d5a05e7cbb9 to your computer and use it in GitHub Desktop.
Kotlin SpannableStringBuilder DSL
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
package tylerwalker.io.dsl | |
import android.graphics.Color | |
import android.text.Spannable | |
import android.text.SpannableStringBuilder | |
import android.text.style.ForegroundColorSpan | |
class Atom(val content: SpannableStringBuilder) { | |
operator fun String.unaryPlus() { content.append(this) } | |
fun append(block: Atom.() -> Unit) = | |
apply { | |
block() | |
} | |
fun red(block: Atom.() -> Unit) = | |
apply { | |
val redPaint = ForegroundColorSpan(Color.rgb(255, 0, 0)) | |
val start = content.lastIndex + 1 | |
block() | |
val end = content.lastIndex | |
if (end >= start) { | |
content.setSpan(redPaint, start, end + 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE) | |
} | |
} | |
private val redPaint = ForegroundColorSpan(Color.rgb(255, 0, 0)) | |
} | |
operator fun Atom.plus(other: Atom): Atom = Atom(content.append(other.content)) | |
fun spannable(block: Atom.() -> Unit) = | |
Atom(SpannableStringBuilder("")).run { | |
block() | |
content | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment