Use Roboto font for earlier devices

Blather picture Blather · Mar 21, 2012 · Viewed 13.1k times · Source

I would like to use the Roboto font in my Android application and make sure it works for earlier versions of Android that don't have the font installed. I know I can do this by using Typeface.createFromAsset() and then manually setting the font for each of my TextViews/Buttons/Other-Objects. It seems like a big pain to do this for every object I show on the screen though.

My question is, is there a better way to do this? Some helper class or a way to set a custom font in a .xml theme file? Anything automated would be better than manually listing out every object on each screen and changing the font.

Thanks!

Answer

Arnaud picture Arnaud · May 12, 2012

Above accepted answer is correct but I just wanted to supply my implementation here

My utility class:

package com.example.utils;

import android.content.Context;
import android.graphics.Typeface;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class AndroidUtils
{
    private static Typeface robotoTypeFace;

    public static void setRobotoFont (Context context, View view)
    {
        if (robotoTypeFace == null)
        {
            robotoTypeFace = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto/Roboto-Regular.ttf");
        }
        setFont(view, robotoTypeFace);
    }

    private static void setFont (View view, Typeface robotoTypeFace)
    {
        if (view instanceof ViewGroup)
        {
            for (int i = 0; i < ((ViewGroup)view).getChildCount(); i++)
            {
                setFont(((ViewGroup)view).getChildAt(i), robotoTypeFace);
            }
        }
        else if (view instanceof TextView)
        {
            ((TextView) view).setTypeface(robotoTypeFace);
        }
    }
}

How to use it, assuming this is an Activity:

AndroidUtils.setRobotoFont(this, view);

To set the same font to all the TextView you can use the decorView of your activity:

ViewGroup godfatherView = (ViewGroup)this.getWindow().getDecorView();
AndroidUtils.setRobotoFont(this, godfatherView);

If you have adapters or fragments, don't forget to set their font as well.

See here also.