Skip to content

Instantly share code, notes, and snippets.

@odemolliens
Last active February 22, 2016 08:40
Show Gist options
  • Save odemolliens/4d5ff5630b6317397956 to your computer and use it in GitHub Desktop.
Save odemolliens/4d5ff5630b6317397956 to your computer and use it in GitHub Desktop.
FontFactory - improve performance when using custom fonts
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