android字体文件制作教程,Android使用自定义字体
? 安卓開發使用自定義字體應該已經是司空見慣了,今天就來介紹一下如何使用自定義字體的方法。
準備工作
如下圖,首先創建一個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屬性引用字體文件
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);
是不是很簡單了,兩種方法任意選擇。
總結
以上是生活随笔為你收集整理的android字体文件制作教程,Android使用自定义字体的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 二层、三层与四层交换机
- 下一篇: android sina oauth2.