1.将字体文件(例如HYLiangPinXianCuJ.ttf)放到assets目录下
2.自定义MultiFontTextView继承TextView
public class MultiFontTextView extends TextView {
public MultiFontTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
/**
* 初始化字体
* @param context
*/
private void init(Context context) {
//设置字体样式
Typeface typeface = FontCustom.setFont(context);
if(typeface!=null){
setTypeface(FontCustom.setFont(context));
}
}
}
3.FontCustom类,从sharedPreference中读取之前设置的字体名,并对Typeface类进行设置,如果字体名是默认的,不设置Typeface类
public class FontCustom {
/**
* 设置字体
*/
public static Typeface setFont(Context context) {
Typeface tf = null;
String fongUrl = (String) SPUtils.get(context, AppConstants.FONTRESURL, "default");
Log.i("faongturl", "url:" + fongUrl);
if ("default".equals(fongUrl)) {
} else {
//给它设置你传入的自定义字体文件,再返回回来
tf = Typeface.createFromAsset(context.getAssets(), fongUrl);
}
return tf;
}
}
4.接下来直接在布局文件中使用即可
<MultiFontTextView
android:layout_marginTop="@dimen/app_margin_right"
android:layout_gravity="center_horizontal"
android:text="长出一朵花"
android:id="@+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="@dimen/large_text_size"
android:textColor="@color/black"
/>