Android更换字体
2018-08-03 本文已影响121人
小言聊编程
-
首先需要去找一些想使用的 ttf 文件, 去1001 Free Fonts或者Google Fonts找,或者让UI提供
-
然后,将这个文件放在Android项目的 assets 文件夹下面。
Capture.PNG
-
然后就是将这个字体运用到你想要改变的 TextView 上面。
TextView textview = (TextView) findViewById(R.id.your_referenced_textview);
Typeface typeface = Typeface.createFromAsset(getAssets(),"fonts/DS-DIGIB.ttf"); // create a typeface from the raw ttf
textview.setTypeface(typeface); // apply the typeface to the textview
这样基本就可以使用自定义的字体了。
为了优化性能我们可以将自定义字体缓存起来 ,这样就不用每次都去初始化,缓存下字体就能让我们不用一直去操作 Assets 文件夹。
public class FontCache {
private static HashMap<String, Typeface> fontCache = new HashMap<>();
public static Typeface getTypeface(String fontname, Context context) {
Typeface typeface = fontCache.get(fontname);
if (typeface == null) {
try {
typeface = Typeface.createFromAsset(context.getAssets(), fontname);
} catch (Exception e) {
return null;
}
fontCache.put(fontname, typeface);
}
return typeface;
}
}
然后自定义一个TextView 调用如下:
private void applyCustomFont(Context context) {
Typeface customFont = FontCache.getTypeface("SourceSansPro-Regular.ttf", context);
setTypeface(customFont);
}