Android 自定义字体方案
16lz
2021-01-23
在应用中需要配置不同的字体,而 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的字体?
更多相关文章
- Android中Http加载如何得到Cookie和 WebView 加载网页如何得到的
- onConfigurationChanged会重新 OnCreate 的解决方案,onConfigurat
- android异步任务加载数据界面实现
- android:加载html,太宽,适配解决方案。
- 【Android】沉浸式状态栏完美解决方案
- ListView中嵌入button,点击监听无响应的解决方案
- android视频录制、另一部手机实时观看方案
- android studio加载so文件报错:dalvik.system.PathClassLoadero