Last active
February 22, 2016 08:40
-
-
Save odemolliens/4d5ff5630b6317397956 to your computer and use it in GitHub Desktop.
FontFactory - improve performance when using custom fonts
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 java.util.HashMap; | |
import android.content.Context; | |
import android.graphics.Typeface; | |
import android.util.Log; | |
/** | |
* Manage font | |
* @author Olivier Demolliens. @odemolliens | |
*/ | |
public class FontFactory { | |
private static FontFactory instance; | |
private HashMap<String, Typeface> fontMap = new HashMap<String, Typeface>(); | |
private Context context; | |
private FontFactory(Context context) { | |
this.context = context.getApplicationContext(); | |
} | |
public static FontFactory getInstance(Context context) { | |
if(instance == null){ | |
return instance = new FontFactory(context); | |
} else { | |
return instance; | |
} | |
} | |
public Typeface getFont(String font) { | |
Typeface typeface = fontMap.get(font); | |
if (typeface == null) { | |
try { | |
typeface = Typeface.createFromAsset(context.getResources().getAssets(), "fonts/" + font); | |
fontMap.put(font, typeface); | |
} catch (Exception e) { | |
Log.e("FontFactory", "Could not get typeface: " + e.getMessage() + " with name: " + font); | |
return null; | |
} | |
} | |
return typeface; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment