Created
April 22, 2019 06:36
-
-
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.
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
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] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
USAGE
view.typeface = FontsHelper[Context Reference, Font file name with extension]