Skip to content

Instantly share code, notes, and snippets.

@osrl
Created November 23, 2018 18:39
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 osrl/065ebff8651c5adf8772958643ccb7c7 to your computer and use it in GitHub Desktop.
Save osrl/065ebff8651c5adf8772958643ccb7c7 to your computer and use it in GitHub Desktop.
...
<string name="foo">Foo<annotation color="@color/dark_see_green" font="@font/montserrat_medium">bar</annotation></string>
...
fun TextView.applySpanAnnotations() {
val annotations = (text as? SpannedString)
?.getSpans(0, text.length, Annotation::class.java) ?: return
text = SpannableString(text)
.apply {
loop@ for (annotation in annotations) {
when(annotation.key) {
"font" -> {
val fontName = annotation.value
val id = resources.getIdentifier(fontName, null, context.packageName)
if (id == 0) continue@loop
val typefaceSpan = CustomTypefaceSpan(ResourcesCompat.getFont(context, id))
setSpan(typefaceSpan,
getSpanStart(annotation),
getSpanEnd(annotation),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
}
"color" -> {
val colorName = annotation.value
val id = resources.getIdentifier(colorName, null, context.packageName)
if (id == 0) continue@loop
val colorSpan = ForegroundColorSpan(ContextCompat.getColor(context, id))
setSpan(colorSpan,
getSpanStart(annotation),
getSpanEnd(annotation),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
}// when
}// for
}// apply
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment