如何更改Android应用程序上面的lollipop版本的默认字体?

时间:2016-10-07 09:59:57

标签: android fonts

我是android开发的新手,我需要为我编写的整个应用程序设置自定义字体:

Operation #1 should finish after Operation #0
Operation #2 should finish after Operation #1
Operation #3 should finish after Operation #2
Operation #4 should finish after Operation #3
Operation #5 should finish after Operation #4
Operation #6 should finish after Operation #5
Operation #7 should finish after Operation #6
Operation #0 starts
Operation #0 finished
Operation #1 starts
Operation #1 finished
Operation #2 starts
Operation #2 finished
Operation #3 starts
Operation #3 finished
Operation #4 starts
Operation #4 finished
Operation #5 starts
Operation #5 finished
Operation #6 starts
Operation #6 finished
Operation #7 starts
Operation #7 finished

我在应用程序类中调用它:

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);
            }
        }
    }
}

我的字体在棒棒糖或以上版本中无效,我也试过这种方法Custom Fonts not working in lollipop?如何创建支持所有版本的自定义字体提前感谢

3 个答案:

答案 0 :(得分:0)

添加此库编译&#39; me.anwarshahriar:书法家:1.0&#39;

和你的onCreate中的这段代码

Calligrapher calligrapher = new Calligrapher(this);
calligrapher.setFont(this, "fonts/calibri.ttf", true);

答案 1 :(得分:0)

此SO帖子已经通过 tomrozb 精美地回答了How to set default font family for entire Android app。只需将其添加到您的values-21.xml文件中

答案 2 :(得分:0)

最后我找到了解决方案,所以我想分享我的解决方案以供将来学习我已经覆盖了值-21文件中的默认字体需要删除主题中的字体项以便使用自定义字体。