如何让我们的应用不受系统字体的影响呢?下面小编将介绍下如何在Android应用里面使用自定义的字体库。
前言:谨慎在listview/gridview中使用自定义字体,因为渲染耗时长,容易造成卡顿。
1、assets/fonts下面是我们要使用的字体库文件。完整路径:assets/fonts/msyh.ttf
2、核心代码是CustomMsyhTV.java。CustomMsyhTV继承自TextView,在初始化的时候读取自定义的字体库。
public class CustomMsyhTV extends TextView {
public CustomMsyhTV(Context context) {
super(context);
init(context);
}
public CustomMsyhTV(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public CustomMsyhTV(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
/***
* 设置字体
* @return
*/
public void init(Context context) {
AssetManager assetMgr = context.getAssets();
Typeface font = Typeface.createFromAsset(assetMgr,"fonts/msyh.ttf");
setTypeface(font);
}
}
3、然后在布局文件中,像普通的TextView一样,引用我们自定义的这个文件。
<com.guan.o2o.view.CustomHanzTV
android:id="@+id/tv_recom_code"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:text="@string/recom_code"
android:textColor="@color/white"
android:textSize="@dimen/TEXT_SIZE_16SP"
/>
4、在Activity只是负责展示我们自定义的这个TextView。