Android 修改应用中的字体

来源:互联网 发布:医疗网络营销策划 编辑:程序博客网 时间:2024/05/29 04:32

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、实际使用

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

原创粉丝点击