Created
July 8, 2017 19:58
-
-
Save AllanHasegawa/44e9bb3fc9cd43f7f024104cffa8dd5e to your computer and use it in GitHub Desktop.
Android Async Font Typeface Loading
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 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