android 更改整个应用字体

来源:互联网 发布:添加路由 linux 编辑:程序博客网 时间:2024/05/16 11:34

单独设置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 0
原创粉丝点击