有时候为了app的美观可能会使用第三方字体,下面介绍几种app使用第三方字体的方法。
第一种,通过反射全局设置app字体,这个方法简单、粗暴、高效,推荐使用,下面介绍怎么使用。
1、首先继承application类并重写oncreate方法
2、通过反射方式设置资源字体
public class App extends Application {
public static Typeface typeFace;
@Override
public void onCreate() {
super.onCreate();
//在app启动创建时调用
setTypeface();
}
/**
* 通过反射方法设置app全局字体
*/
public void setTypeface(){
typeFace = Typeface.createFromAsset(getAssets(), "fonts/aaa.ttf");
try
{
Field field = Typeface.class.getDeclaredField("SERIF");
field.setAccessible(true);
field.set(null, typeFace);
}
catch (NoSuchFieldException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
}
}
3、在manifest文件中配置application和主题
4、主题中加入<itemname="android:typeface">serif</item>
需要注意的的对于父主题的选择上,不要使用android:Theme.DeviceDefault开始的主题,因为这样就反射设置的字体就无法生效。
第二种,单个设置textview,这样比较的麻烦,textview有一个setTypeFace()方法,这样就能改变字体样式,这个方法不推荐使用。
第三种,比如说要所有的textview都要用第三方字体,那么就重写TextView,上面也说了textview有setTypeFace方法,将某人的字体替换成我们想要的就可以了。
public class CusFntTextView extends TextView {
public CusFntTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public CusFntTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CusFntTextView(Context context) {
super(context);
init();
}
private void init() {
if (!isInEditMode()) {
Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "Futura.ttf");
setTypeface(tf);
}
}
第四种,github上有个开源的库简单的设置下就能使用字体,贴上介绍的帖子
点击访问
第五种,遍历根节点,依次为字控件设置字体,不推荐这样使用,效率不高,浪费资源体验也不好
最后贴上效果图和demo的下载地址 点击下载