两种方法:
方法一:
在assets目录下新建目录fonts,然后存放自己的字体库,我这里是微软雅黑weiruanyahei.ttf。
TextView tv;
Typeface tf2 = Typeface.createFromAsset(getAssets(),"fonts/weiruanyahei.ttf");
tv.setTypeface(tf2);
方法二:建立基类,xml统一使用
package com.insight.androidfont;
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
public class FontTextView extends 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);
}
}
}
下面是布局:
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="69dp"
typefaceName="weiruanyahei"
android:text="FontTextView"
android:textSize="30sp" />
大字体是要设置的属性,weiruanyahei是字体库的名字