在应用中需要配置不同的字体,而 Android 只能在 xml 中配置系统默认提供的四种字体,需要自定义的字体都需要在 Java 代码中配置.
Android 默认方案
你可以通过ID查找到View,然后挨个为它们设置字体。字体放置于 assets/fonts 文件夹下面.
Typeface customFont = Typeface.createFromAsset(this.getAssets(), "fonts/YourCustomFont.ttf");
TextView view = (TextView) findViewById(R.id.activity_main_header);
view.setTypeface(customFont);
改良
如果每次都这样加载,界面就会卡顿,所以我提取出来了一个工具类.
示例中涉及到了两个自定义的字体,用枚举实现了单例模式,将字体存储在静态变量中,避免每次都去 assets 中加载,更改之后页面就流畅了.
public enum TypefaceUtils {
TYPEFACE;
private static Typeface typeface50;
private static Typeface typeface55;
public void set50Typeface(TextView textView) {
if (typeface50 == null)
typeface50 = Typeface.createFromAsset(textView.getContext().getAssets(), "fonts/HYQiHei-50S.otf");
textView.setTypeface(typeface50);
}
public void set55Typeface(TextView textView) {
if (typeface55 == null)
typeface55 = Typeface.createFromAsset(textView.getContext().getAssets(), "fonts/HYQiHei-55S.otf");
textView.setTypeface(typeface55);
}
}