Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.