在应用中需要配置不同的字体,而 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);    }}

参考链接

  • 【译】Android:更好的自定义字体方案
  • Android如何高效率的替换整个APP的字体?

更多相关文章

  1. Android中Http加载如何得到Cookie和 WebView 加载网页如何得到的
  2. onConfigurationChanged会重新 OnCreate 的解决方案,onConfigurat
  3. android异步任务加载数据界面实现
  4. android:加载html,太宽,适配解决方案。
  5. 【Android】沉浸式状态栏完美解决方案
  6. ListView中嵌入button,点击监听无响应的解决方案
  7. android视频录制、另一部手机实时观看方案
  8. android studio加载so文件报错:dalvik.system.PathClassLoadero

随机推荐

  1. android 查看图片、保存图片
  2. 苦逼啊--qt for android 5.4.1 camera
  3. android canvas使用line画半园
  4. android下载安装APK
  5. android 监听其它app的错误或者崩溃的方
  6. Android: activity的过渡动画
  7. Android PhotoView 使用教程
  8. Android双击
  9. android menu自定义菜单 Demo
  10. android > 屏蔽掉返回键