Setting custom font to all TextViews

If you need to set one font for all TextViews in android application you can use this solution. It will override ALL TextView's typefaces, includes action bar and other standard components, but EditText's password font won't be overriden.

MyApp.java

    public class MyApp extends Application {

    @Override
    public void onCreate()
    {
                TypefaceUtil.overrideFont(getApplicationContext(), "SERIF", "fonts/Roboto-Regular.ttf"); 
     }
    }

TypefaceUtil.java

public class TypefaceUtil {

    /**
     * Using reflection to override default typeface
     * NOTICE: DO NOT FORGET TO SET TYPEFACE FOR APP THEME AS DEFAULT TYPEFACE WHICH WILL BE OVERRIDDEN
     * @param context to work with assets
     * @param defaultFontNameToOverride for example "monospace"
     * @param customFontFileNameInAssets file name of the font from assets
     */
    public static void overrideFont(Context context, String defaultFontNameToOverride, String customFontFileNameInAssets) {
        try {
            final Typeface customFontTypeface = Typeface.createFromAsset(context.getAssets(), customFontFileNameInAssets);

            final Field defaultFontTypefaceField = Typeface.class.getDeclaredField(defaultFontNameToOverride);
            defaultFontTypefaceField.setAccessible(true);
            defaultFontTypefaceField.set(null, customFontTypeface);
        } catch (Exception e) {
            Log.e("TypefaceUtil","Can not set custom font " + customFontFileNameInAssets + " instead of " + defaultFontNameToOverride);
        }
    }
}

themes.xml

     <?xml version="1.0" encoding="utf-8"?>
   <resources>
     <style name="MyAppTheme" parent="@android:style/Theme.Holo.Light">
    <!-- you should set typeface which you want to override with TypefaceUtil -->
    <item name="android:typeface">serif</item>
   </style>
   </resources>

Update for Android 5.0 or greater

As i have investigated and tested on device running api 5.0 or greater this solution is working fine because i am using the single style.xml file and not making other style.xml in values-21 folder

Although Some users asking me that this solution not working with android 5.0 device (they may be using values-21 style.xml i guess)

So that is because Under API 21, most of the text styles include fontFamily setting, like

<item name="fontFamily">@string/font_family_body_1_material</item>

Which applys the default Roboto Regular font:

<string name="font_family_body_1_material">sans-serif</string>

So the best solution is

If Any one having problem not working for 5.0+. Don't override typeface in your values-v21 styles.

Just override font in values/style.xml and you will good to go :)

Tags:

Fonts

Android