Android加载自定义字体出错,Android使用自定义字体

​ 安卓开发使用自定义字体应该已经是司空见惯了,今天就来介绍一下如何使用自定义字体的方法。

准备工作

如下图,首先创建一个assets文件夹,然后新建一个fonts子文件夹,放入字体文件。

731209562e80

微信截图_20170816115004.png

方法一:通过重写TextView实现在xml中配置

1.重写TextView

private Context mContext;

private String TypefaceName = "";

public String getTypefaceName() {

return TypefaceName;

}

public void setTypefaceName(String typefaceName) {

TypefaceName = typefaceName;

Typeface typeface = Typeface.createFromAsset(mContext.getAssets(), "fonts/" + TypefaceName + ".ttf");

this.setTypeface(typeface);

System.gc();

}

public FontTextView(Context context, AttributeSet attrs, int defStyle) {

super(context, attrs, defStyle);

this.mContext = context;

int resouceId = attrs.getAttributeResourceValue(null, "typefaceName", 0);

if (resouceId != 0) {

TypefaceName = context.getResources().getString(resouceId);

} else {

TypefaceName = attrs.getAttributeValue(null, "typefaceName");

}

if (TypefaceName != null && !"".equals(TypefaceName)) {

Typeface typeface = Typeface.createFromAsset(context.getAssets(), "fonts/" + TypefaceName + ".ttf");

this.setTypeface(typeface);

}

}

public FontTextView(Context context, AttributeSet attrs) {

super(context, attrs);

this.mContext = context;

// 先判断是否配置的资源文件

int resouceId = attrs.getAttributeResourceValue(null, "typefaceName", 0);

if (resouceId != 0) {

TypefaceName = context.getResources().getString(resouceId);

} else {

TypefaceName = attrs.getAttributeValue(null, "typefaceName");

}

if (TypefaceName != null && !"".equals(TypefaceName)) {

Typeface typeface = Typeface.createFromAsset(context.getAssets(), "fonts/" + TypefaceName + ".ttf");

this.setTypeface(typeface);

}

}

public FontTextView(Context context) {

super(context);

this.mContext = context;

// TypefaceName = attrs.getAttributeValue(null, "TypefaceName");

if (TypefaceName != null && !"".equals(TypefaceName)) {

Typeface typeface = Typeface.createFromAsset(context.getAssets(), "fonts/" + TypefaceName + ".ttf");

this.setTypeface(typeface);

}

}

}

2.xml使用typefaceName属性引用字体文件

android:layout_width="60dp"

android:layout_height="50dp"

android:textSize="20sp"

typefaceName="Simhei"

android:text="This is first child view"/>

方法二:代码内部设置

加载字体资源文件:

需要注意的是,字体文件加载不要放在主线程中,会阻塞线程,影响性能

public static Typeface typeFace =Typeface.createFromAsset(getContext().getAssets(),

"fonts/Simhei.ttf");

public static Typeface typeFaceArial= Typeface.createFromAsset(getContext().getAssets(),

"fonts/Arial.ttf");

使用:

TextView.setTypeface(typeFace);

是不是很简单了,两种方法任意选择。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值