1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > android的自定义字体 Android 自定义字体方案

android的自定义字体 Android 自定义字体方案

时间:2021-03-13 12:49:30

相关推荐

android的自定义字体 Android 自定义字体方案

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

}

}

参考链接

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。