Created
November 23, 2018 18:39
-
-
Save osrl/065ebff8651c5adf8772958643ccb7c7 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
... | |
<string name="foo">Foo<annotation color="@color/dark_see_green" font="@font/montserrat_medium">bar</annotation></string> | |
... |
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
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