Skip to content

Instantly share code, notes, and snippets.

@AllanHasegawa
Created July 8, 2017 19:58
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 AllanHasegawa/44e9bb3fc9cd43f7f024104cffa8dd5e to your computer and use it in GitHub Desktop.
Save AllanHasegawa/44e9bb3fc9cd43f7f024104cffa8dd5e to your computer and use it in GitHub Desktop.
Android Async Font Typeface Loading
object FontCache {
private val FONTS_DIR = "fonts/"
private val CACHE = Hashtable<String, Typeface>()
fun notoSansCJK(context: Context, textView: TextView) {
applyTypefaceAsync(context, textView, "NotoSansCJKjp-Regular.otf")
}
fun applyTypefaceAsync(context: Context, textView: TextView, typefaceName: String) {
val weakRef = WeakReference(textView)
Observable
.fromCallable {
synchronized(CACHE) {
get(context, typefaceName)
}
}
.subscribeOn(Schedulers.io())
.observeOnViewMainThread()
.subscribe {
it?.let { typeface -> weakRef.get()?.typeface = typeface }
}
}
private fun get(context: Context, name: String): Typeface? {
val fileName = FONTS_DIR + name
return CACHE.getOrPut(fileName) {
try {
val start = SystemClock.elapsedRealtime()
val font = Typeface.createFromAsset(context.assets, fileName)
val end = SystemClock.elapsedRealtime()
logd { "Loaded font [$name] in ${end - start}ms." }
font
} catch (e: Exception) {
null
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment