Created
August 1, 2013 07:59
-
-
Save pfn/6129347 to your computer and use it in GitHub Desktop.
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
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