Android应用使用第三方字体

有时候为了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的下载地址   点击下载



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值