How to use custom fonts in Android apps (and not get fat)

Fonts have always been a vital part of brand identity and UI design. With the development of modern Web standards it has become easy to implement customized fonts in websites, but native mobile apps somehow still lag behind in this area. Platform guides warn us against unleashing our creativity in that aspect and state that the built-in fonts have been optimized for memory and performance constraints of mobile devices. I think today, with more and more horse power under the hood of our latest mobile gadgets, we should not limit ourselves to the modest assortment of default typefaces.

Going the hard way

Using custom fonts in Android is not that straightforward. In TextViews, for instance, there is the fontFamily tag, but it only lets you pick one of the built-in typefaces. You can call setTypeface() for each TextView, but this is cumbersome to say the least. The most popular approach is to define your own tag that inherits from the TextView. Then you can even have a global setting for the typeface, but you still have to manually replace all the TextViews in your app with this new tag (and there will be no fewer than hundreds of them). You’ll also have to implement and replace all the other views that use texts, like EditText, Button and many more. And lastly, beware of calling Typeface.createFromAsset() for each text instance as your app will literally explode at some point. Does all this sound encouraging?..

If you google for “custom fonts in Android”, you’ll find lots of recipes on stackoverflow.com. If you want to take the long path of either manually implementing custom fonts in your app or trying a dozen of different libraries out there, go ahead. But if you simply don’t have that time, keep reading. I’ve been there, done that. Find out what I discovered.

Calligraphy now!

As you may already know, I’m a big fan of simple and elegant solutions that still allow customization. My winner is Christopher Jenkins’ Calligraphy library (https://github.com/chrisjenx/Calligraphy). Here’s why:

  1. You don’t have to introduce your own overridden TextView component, you use the built-in TextView.
  2. You can easily include the library using gradle.
  3. The library doesn’t limit your choice of fonts; you just add your preferred ones to the assets directory.
  4. Not only do you get custom text views — all the other text-based Android components will also be displayed using your preferred font.

And why it’s elegant? Below’s everything you need to do to use a custom font in your app.

Add the library in gradle’s dependencies section:

compile 'uk.co.chrisjenx:calligraphy:0.7.+'

Place custom font(s) in the assets/fonts directory of your app.

Override the default Application class and initialize Calligraphy with your default font:

public class Application extends android.app.Application {
    @Override
    public void onCreate() {
        super.onCreate();
        CalligraphyConfig.initDefault("fonts/your-font.ttf");
    }
}

Register your Application class in the manifest:

<application
    android:name=".Application"
    ...  >

Add this call to your activities:

@Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(new CalligraphyContextWrapper(newBase));
}

And you’re good to go. Every text in your app will use the custom font. If you want some of the views to use a different font, use android:fontFamily="fonts/your-other-font.ttf" or define a separate style for that (see Calligraphy documentation on GitHub).

Weigh your fonts

Sometimes, when it’s all that simple, we tend to turn off caution and lose our common sense. When there are fast-food booths all over the city, we devour juicy hamburgers every day for launch and — to our inexplicable surprise — get fat. Custom fonts can also make our apps chubby. Firstly, a good UI design should include no more than one or two typefaces, otherwise your apps will look like those glittering toys on a chinatown market. Secondly, if you find your favorite font larger than hundred-and-something kilobytes… hold on and think.

One reason might be that your font is made of overly complex glyphs (elementary symbols) that are just not made for small screen and limited memory. Always begin selecting your fonts with displaying them with the planned size on a real device. If they’re hard to read, find something less elaborate. Remember that mobile users are always on the go, so the contents have to be legible and clear. But that’s a designer’s job.

Way more often a font is fatty because it contains hundreds or thousands of glyphs for many different languages. It’s nice that a font designer has created Cyrillic, Greek, Hebrew, Arabic and Chinese variants and put them in one ttf/otf file, but do you really need them all in your app? If you don’t plan to localize it to some or any of these languages, cherry-pick the glyphs you need (it’s called font subsetting). To do that, you can use FontForge, an open-source app for manipulating fonts. It is free, versatile, but also ugly and hard to use. Subsetting is not an easy task with FontForge as you have to manually delete the glyphs you don’t need. My favorite here is fontsquirrel @font-face generator — a web-based app that lets you upload the font, show the number of glyphs contained in the font definition and, more importantly, allows you to pick the Unicode tables (character sets) you want to limit your font to (switch to the expert mode to do that). Then you just download the subsetted font file and find out that it shrunk from, say, 1 MB to 50 kilobytes. Voila! (By the way, you can follow the same procedure to slim down your Web pages and conserve bandwidth.)

Finally, don’t forget to make sure that the cost of using a custom font is not too high performance-wise. Get one of the older devices you target your app at, use your preferred profiling tool and check memory and CPU usage before and after implementing the new typeface.

Last but not least — copyright

It’s obvious that you have to observe intellectual property of the font maker, so read the legal notices and decide whether they allow you to use the font for free. Keep in mind that a well-designed font is a work of art and its author deserves the money for the job. Don’t cheat. If moral arguments don’t appeal to you, remember that once your app goes live it becomes publicly available and you may have to face legal action against you. There’s also a caveat related to subsetting fonts — even though you don’t touch the glyphs themselves, by manipulating a font file you create a derivative work, and an otherwise free license may not allow that. Then it’s best to contact the author, describe your case and ask for permission.

15 comments

  1. Avail The Finest Tech Support From Expert Technicians

    In this era of advanced computers and technology, it is really difficult to imagine our life without computers, laptops, printers, internet or any device. Be it on the professional front or personal use, once cannot deny the impact that these gadgets have made in our lifestyle. However, issues with these devices are quite common and it is important to troubleshoot these problems completely.

    Eradicate computer problems with Online Tech Repairs Inc

    Online Tech Repairs Support is the best and the most comfortable option available for users, to fix any kind of problem related to computer and its related devices. For more than 10 years, Online Tech Repairs is one of the leading and trustworthy technical support company which has been providing the best online computer support to users in the USA and Canada.

    They have a team of Microsoft Certified Technicians who will help you to troubleshoot all your computers and related issues as soon as possible. Not only, they will fix your problem, but also they will optimize your system for better performance and enhance the security and performance. Our experts start the diagnosis process from the beginning and try every possible step to resolve your problem quickly. Their years of experience have made them the master in providing the excellent technical support services.

    PC Smart Care online tech support provides complete fixation of your system issues over phone, live chat or email. Our customers are our testament and we believe to resolve your problems. That is why we aim to provide you 99% first call resolution rate and 100% customer satisfaction with our technical support services.

    We, at Online Tech Repairs Incmake an effort to solve all your technical problems with these steps:

    • Speak

    • Connect

    • Solve

    Moreover, our hard work speaks for itself as we have more than 50,000 satisfied customers all over the USA and Canada. Through the method of secure remote access, our technical engineers offer diagnosis and troubleshooting of your system and network via connecting your system with ours. You don’t need to worry, as this method is completely safe and encrypted.

    Our traits don’t just include affordable price plans but also you can call us for free consultation. And our experts will help you know and analyze your current computer and network status. While other technical support company tries to gain as much money as possible and their “technicians” are just script reading robots, Online Tech Repairstends to deliver top-notch benefits and tech support services by running scan, rebooting of system, or install anti-virus program.

    Avail Maximum Benefits WithOnline Tech Repairs SUPPORT

    • Microsoft Certified Technicians

    • 24×7, round the clock service

    • Multiple Brand Support

    • Free diagnosis of your system and network

    • 99% first call resolution rate

    • Affordable Plans

    • Easily available

    • Instant Support

    • 100% customer satisfaction

    • Quick Resolution

    • Secured Remote Access

    • No Fix, No Pay

    • Easy connection via phone, chat or e-mail

    Call us at our toll free number anytime, any day and we are available for you to provide the best online tech support for the following:

    • Router Support

    • Wi–Fi Support

    • Printer Support

    • System Support

    • Microsoft Office Support

    • Virus Removal Support

    • Windows Support

    Say No To Issues With ONLINE TECH REPAIRS Support

    You are just one-step away in eradicating all your system issues. Don’t wait! Call us today at our toll free number 1-888-961-4986 using DISCOUNT CODE (otr214426)now. Connect with us and get the best online computer support experience with ONLINE TECH REPAIRS.

  2. This tool is great. Others was making the app laggy but this one doesn’t cause any lag at all. Thanks to the developer and you the presenter :))

  3. hi Daniel, do you know how I can include this library in Android Studio? I couldn’t open the example or include it. Thanks!

  4. Hi Daniel, nice article… I have a little problem: now, I see the text twice, my text with the custom font and the android default text behind it

  5. Pingback: Pirate Kings Hack
  6. Hi, is that possible to preview the font inside Android Studio, without running the application? I mean, inserting a TextView with that custom font inside a layout and preview how it is gonna look like statically – with no need for running the application to see the result.

  7. Hi, is that possible to preview the font inside Android Studio, without running the application? I mean, inserting a TextView with that custom font inside a layout and preview how it is gonna look like statically – with no need for running the application to see the result.

    1. Unfortunately this would require AS’s visual builder to support Calligraphy and I don’t think they will implement such support in a foreseeable future.

  8. How to use above solution with Eclipse Gradle Plugin regarding the addition of the library in gradle’s dependencies..?

    1. Prashant, frankly speaking, I haven’t used Eclipse for Android development since the advent of Android Studio, and now I think AS got really mature and Eclipse is dying in the world of Android, but I think adding a dependency as defined in https://github.com/chrisjenx/Calligraphy should be all you need.

  9. use in fragment: return getActivity().getLayoutInflater().inflate(R.layout.description_frag, container, false);

    for tabtitle:
    Create class CustomTabLayout

    import android.content.Context;
    import android.graphics.Typeface;
    import android.support.design.widget.TabLayout;
    import android.support.v4.view.PagerAdapter;
    import android.support.v4.view.ViewPager;
    import android.support.v7.widget.AppCompatTextView;
    import android.util.AttributeSet;
    import android.view.ViewGroup;

    public class CustomTabLayout extends TabLayout {
    private Typeface mTypeface;

    public CustomTabLayout(Context context) {
    super(context);
    init();
    }

    public CustomTabLayout(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
    }

    public CustomTabLayout(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init();
    }

    private void init() {
    mTypeface = Typeface.createFromAsset(getContext().getAssets(), “fonts/josefinsans_regular.ttf”); // here you will provide fully qualified path for fonts
    }

    @Override
    public void setupWithViewPager(ViewPager viewPager) {
    super.setupWithViewPager(viewPager);

    if (mTypeface != null) {
    this.removeAllTabs();
    ViewGroup slidingTabStrip = (ViewGroup) getChildAt(0);

    PagerAdapter adapter = viewPager.getAdapter();

    for (int i = 0, count = adapter.getCount(); i < count; i++) {
    Tab tab = this.newTab();
    this.addTab(tab.setText(adapter.getPageTitle(i)));
    AppCompatTextView view = (AppCompatTextView) ((ViewGroup) slidingTabStrip.getChildAt(i)).getChildAt(1);
    view.setTypeface(mTypeface, Typeface.NORMAL);
    }
    }
    }

    }

Comments are closed.