Android Toolkit: Calligraphy for custom fonts
UPDATE: When this post was first written (2015) the most recent Android Version was Marshmallow. As of October 2020, less than 6% of Android devices use this version, as such this article should be considered “deprecated”: But since then using custom fonts has become an easy task.
With Android 8.0 we were introduced to the Resource “Fonts”.
For you to use this resource all you have to do is create a folder named Font inside the Res folder and copy your font inside it (note: All font names must be: lowercase a-z, 0-9, or underscore).
For you to use your font programmatically simply use:
textView.setTypeface(ResourcesCompat.getFont(context, R.font.foo_font))
or you can easily use the XML attribute
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="@font/abc_font" />
THE CONTENT BELLOW SHOULD BE CONSIDERED DEPRECATED
Android would be boring if all apps only used the Roboto typeface. But when a designer asks you to add another font, you start thinking about subclassing a lot of Views.
Calligraphy takes care of that for you. You just need to:
- Add the library to your build file
- Place your font file(s) in the
assets/fronts
folder - Use
fontPath
:
<TextView fontPath="fonts/MyFont.ttf"/>
Want to set a default font and forget about it? Add this to your Application
class:
@Override public void onCreate() { super.onCreate(); CalligraphyConfig.initDefault( new CalligraphyConfig.Builder() .setDefaultFontPath("fonts/MyFont.ttf") .setFontAttrId(R.attr.fontPath) .build() ); //.... }
You can still use fontPath
to override the default.
More information on the Calligraphy GitHub page.