Android 修改应用中的字体

1、下载ttf格式的字体文件

比如:华康娃娃字体,可以在我的资源页下载,点我


2、 放入资源目录中

这里写图片描述


3、 局部替换

针对要显示的TextView设置不同的Typeface

将一个ttf字库构造成一个Typeface,将构造的Typeface设置到要显示的TextView。

 private static Typeface typeface;
    public static Typeface getTypeface(Context context){
        if (typeface == null) {
            typeface = Typeface.createFromAsset(context.getAssets(), "fonts/hkwwzt.ttf");
        }
        return typeface;
    }

在代码中使用

TextView tv = new TextView(this);
tv.setTypeface(getTypeface(context));

这样使用就需要重复写很多相同的代码,显然不符合程序员的身份(^o^)/~


4、自定义控件

只要是需要使用到该字体的控件都可以这样进行自定义

1、 自定义TextView

public class ZTextView extends TextView {

    public ZTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        Typeface typeface = Typeface.createFromAsset(context.getAssets(), "fonts/hkwwzt.ttf");
        setTypeface(typeface);
    }
}

2、 自定义EditText

public class ZEditText extends EditText {

    public ZEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        Typeface typeface = Typeface.createFromAsset(context.getAssets(), "fonts/hkwwzt.ttf");
        setTypeface(typeface);
    }
}

3、 自定义Button

public class ZButton extends Button {

    public ZButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        Typeface typeface = Typeface.createFromAsset(context.getAssets(), "fonts/hkwwzt.ttf");
        setTypeface(typeface);
    }
}

怎么样简单吧,只是换一个字体。如果需要更换更多字体,我建议使用全局变量替换字体路径”fonts/hkwwzt.ttf”方便更换。


5、实际使用

在实际使用中我还是喜欢使用自定义控件实现更换字体,因为这样简单,只用更换写一次代码,全局可用,而且如果后面需要更换字体时也简单,并且如果项目中有的地方不需要更换字体那就使用原始控件就好了,灵活。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值