Among other nice things that Android has, we can also load custom fonts.
To do that we need to get a font file with the desired font. There are some sites where you can find open source fonts like this or this.Ok, I assume you downloaded this font file angrybirds-regular.ttf .
To do that we need to get a font file with the desired font. There are some sites where you can find open source fonts like this or this.Ok, I assume you downloaded this font file angrybirds-regular.ttf .
Step 1:
– put the font file in the android assets directory
Step 2:
Create a util class that we will use it when we need to load our font:
/**
* Used to load fonts from the assets directory
*
* @author Catalin Prata
* Date: 04/22/13
*/
public class FontUtils {
// font file name
public static final String FONT_ANGRY_BIRDS = "angrybirds-regular.ttf";
// store the opened typefaces(fonts)
private static final Hashtable<String, Typeface> mCache = new Hashtable<String, Typeface>();
/**
* Load the given font from assets
*
* @param fontName font name
* @return Typeface object representing the font painting
*/
public static Typeface loadFontFromAssets(String fontName) {
// make sure we load each font only once
synchronized (mCache) {
if (!mCache.containsKey(fontName)) {
Typeface typeface = Typeface.createFromAsset(ApplicationProvider.context().getAssets(), fontName);
mCache.put(fontName, typeface);
}
mCache.get(fontName);
}
}
}
Step 3:
– use the font load method to set the font of a TextView:
// I assume that myTextView is an instance of a TextView class and it is the text view that I want to have the custom font myTextView.setTypeface(FontUtils.loadFontFromAssets());
When you use custom fonts and load them from the assets multiple times you might get some crashes, with the class above, you won’t have any problems.
I hope it will help you! :)
