Skip to content

Instantly share code, notes, and snippets.

@tizisdeepan
Created April 22, 2019 06:36
Show Gist options
  • Save tizisdeepan/583a0fee2ea2de44ca3cfa20a26e1853 to your computer and use it in GitHub Desktop.
Save tizisdeepan/583a0fee2ea2de44ca3cfa20a26e1853 to your computer and use it in GitHub Desktop.
A Fonts Cache mechanism that can be used in your project right away. Do you know that creating a typeface object from resources every time you set a font to your views is memory expensive? Use this simple helper class to avoid such memory leaks and improve your app's performance.
import android.content.Context
import android.graphics.Typeface
import com.zoho.zohosocial.utils.MLog
import java.util.*
object FontsHelper {
private val TAG = "TypefaceHelper"
private val fontsCache = Hashtable<String, Typeface>()
operator fun get(c: Context, assetPath: String): Typeface? {
if (!fontsCache.containsKey(assetPath)) {
try {
fontsCache[assetPath] = Typeface.createFromAsset(c.assets, "fonts/$assetPath")
} catch (e: Exception) {
MLog.e(TAG, "Could not get typeface '" + assetPath + "' because " + e.message)
return null
}
}
return fontsCache[assetPath]
}
}
@tizisdeepan
Copy link
Author

USAGE

view.typeface = FontsHelper[Context Reference, Font file name with extension]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment