Skip to content

Instantly share code, notes, and snippets.

@pfn
Created August 1, 2013 07:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pfn/6129347 to your computer and use it in GitHub Desktop.
Save pfn/6129347 to your computer and use it in GitHub Desktop.
object SpannedGenerator {
private def span(style: Object, text: CharSequence) = {
val s = new SpannableString(text)
s.setSpan(style, 0, text.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
s
}
def textColor(color: Int, text: CharSequence) =
span(new ForegroundColorSpan(color) , text)
def bold(text: CharSequence) = span(new StyleSpan(Typeface.BOLD) , text)
def italics(text: CharSequence) = span(new StyleSpan(Typeface.ITALIC), text)
}
case class SpannedGenerator(fmt: String) {
def formatSpans(items: CharSequence*): Spanned = {
val builder = new SpannableStringBuilder()
val idx = fmt indexOf "%"
formatNext(builder, fmt, 0, idx, items:_*)
builder
}
private def formatNext(s: SpannableStringBuilder, fmt: String,
cur: Int, next: Int, items: CharSequence*) {
if (next == -1) {
s.append(fmt.substring(cur, fmt.length))
} else {
s.append(fmt.substring(cur, next))
val space = fmt.indexWhere({ !_.isDigit }, next + 1)
val number = fmt.substring(next + 1,
if (space < 0) fmt.length else space).toInt
s.append(items(number - 1))
if (space > 0)
formatNext(s, fmt, space, fmt indexOf ("%", space), items:_*)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment