安卓开发使用自定义字体应该已经是司空见惯了,今天就来介绍一下如何使用自定义字体的方法。
准备工作
如下图,首先创建一个assets文件夹,然后新建一个fonts子文件夹,放入字体文件。
微信截图_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属性引用字体文件
<com.example.scrollerlayout.FontTextView
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);
是不是很简单了,两种方法任意选择。
网友评论