android 更改整个应用字体

单独设置TextView的字体比较简单:

 Typeface fontFace = Typeface.createFromAsset(getAssets(),
                                    "fonts/STXINGKA.TTF");
                    // 字体文件必须是true type font的格式(ttf);
                    // 当使用外部字体却又发现字体没有变化的时候(以 Droid Sans代替),通常是因为
                    // 这个字体android没有支持,而非你的程序发生了错误

                    TextView text = (TextView) findViewById(R.id.ttf);
                    text.setTypeface(fontFace);

如果要设置整个应用的字体就比较麻烦了,一种实现方式是自定义TextView,但是很麻烦,并且button等控件还不能使用。下面介绍一种简单的方式,通过反射实现改变所有的字体。
首先拷贝自定义字体到assets/fonts下,然后在自定义Application中设置改变字体。

public class FontsOverride {
      public static void setDefaultFont(Context context,
                String staticTypefaceFieldName, String fontAssetName) {
            final Typeface regular = Typeface.createFromAsset(context.getAssets(),
                    fontAssetName);
            replaceFont(staticTypefaceFieldName, regular);
        }

        protected static void replaceFont(String staticTypefaceFieldName,
                final Typeface newTypeface) {
            try {
                final Field staticField = Typeface.class
                        .getDeclaredField(staticTypefaceFieldName);
                staticField.setAccessible(true);
                staticField.set(null, newTypeface);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
}

在自定义Application中设置:

 FontsOverride.setDefaultFont(this, "DEFAULT", "fonts/HYXiZYJF.ttf");
         FontsOverride.setDefaultFont(this, "MONOSPACE", "fonts/HYXiZYJF.ttf");
         FontsOverride.setDefaultFont(this, "SERIF", "fonts/HYXiZYJF.ttf");
         FontsOverride.setDefaultFont(this, "SANS_SERIF", "fonts/HYXiZYJF.ttf");

搞定了,测试正常。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值