1

Am new for android development i need to set custom fonts for whole application for that i have written:

public class TypeFaceUtil {
   public static void overrideFont(Context context, String defaultFontNameToOverride, String customFontFileNameInAssets) {
        final Typeface customFontTypeface = Typeface.createFromAsset(context.getAssets(), customFontFileNameInAssets);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Map<String, Typeface> newMap = new HashMap<String, Typeface>();
            newMap.put("SERIF", customFontTypeface);
            try {
                final Field staticField = Typeface.class
                        .getDeclaredField("sSystemFontMap");
                staticField.setAccessible(true);
                staticField.set(null, newMap);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        } else {
            try {
                final Field defaultFontTypefaceField = Typeface.class.getDeclaredField(defaultFontNameToOverride);
                defaultFontTypefaceField.setAccessible(true);
                defaultFontTypefaceField.set(null, customFontTypeface);
            } catch (Exception e) {
                Log.e(TypeFaceUtil.class.getSimpleName(), "Can not set custom font " + customFontFileNameInAssets + " instead of " + defaultFontNameToOverride);
            }
        }
    }
}

and i call it in application class like this:

public class tt extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
       TypeFaceUtil.overrideFont(getApplicationContext(),"SERIF","fonts/calibri.ttf");
    }
}

My fonts is not working in lollipop or above versions and i tried in this method too Custom Fonts not working in lollipop? how to create a custom fonts which supports all version thanks in advance

Community
  • 1
  • 1
M.Yogeshwaran
  • 1,419
  • 4
  • 22
  • 48

3 Answers3

0

add this library compile 'me.anwarshahriar:calligrapher:1.0'

and this code inside your onCreate

Calligrapher calligrapher = new Calligrapher(this);
calligrapher.setFont(this, "fonts/calibri.ttf", true);
amir
  • 145
  • 1
  • 9
0

this SO post has already answered beautifully How to set default font family for entire Android app by tomrozb
Just add this in your values-21.xml file

Community
  • 1
  • 1
Rahul Khurana
  • 8,577
  • 7
  • 33
  • 60
0

Finally i found solution so i like to share my solution for future study i have override the default font in value-21 file need to remove the typeface item in your theme inorder to work with custom fonts.

M.Yogeshwaran
  • 1,419
  • 4
  • 22
  • 48