【问题标题】:How to change default font in android applications above lollipop version?如何在棒棒糖版本以上的 android 应用程序中更改默认字体?
【发布时间】:2016-10-07 09:59:57
【问题描述】:

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

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

我在应用程序类中这样称呼它:

public class tt extends Application {

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

我的字体在棒棒糖或更高版本中不起作用,我也尝试过这种方法Custom Fonts not working in lollipop?如何创建支持所有版本的自定义字体提前感谢

【问题讨论】:

  • 字体不会“工作”,除非您通过调用 textview、按钮或其他视图的 setTypeface() 方法来设置它们。
  • @M.Yogeshwaran 看到我的答案

标签: android fonts


【解决方案1】:

这篇 SO 帖子已经由 tomrozb 很好地回答了 How to set default font family for entire Android app
只需将其添加到您的 values-21.xml 文件中

【讨论】:

    【解决方案2】:

    添加这个库 compile 'me.anwarshahriar:calligrapher:1.0'

    你的onCreate里面的这段代码

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

    【讨论】:

    • 可以在应用类中使用
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多