$Android设置TextView的字体

  做项目的时候,需要使用到手写字体来让内容更加的美观。可是程序中默认使用的是系统的默认字体,怎么将TextView(或EditText)的字体设置成自己想要的字体呢?步骤如下:

  1、下载字体文件(.ttf格式),比如Jinglei.ttf(方正静蕾的字体文件),然后将其复制到项目工程的assets/fonts目录下。

  2、设置TextView的字体:

1 TextView tv = (TextView)findViewById(R.id.my_textview);
2 Typeface typeface = Typeface.createFromAsset(mContext.getAssets(), "fonts/Jinglei.ttf");  // mContext为上下文
3 tv.setTypeface(typeface );

  3、为了使用起来方便,还可以将设置字体的操作封装成一个工具类:

 1 /**
 2  * 字体相关操作工具类
 3  * 
 4  */
 5 public class TypefaceUtil {
 6     // 上下文
 7     private Context mContext;
 8     private Typeface mTypeface;
 9 
10     /**
11      * 如果ttfPath为null那么mTypeface就为系统默认值
12      * 
13      * @param context
14      * @param ttfPath
15      */
16 
17     public TypefaceUtil(Context context, String ttfPath) {
18         mContext = context;
19         mTypeface = getTypefaceFromTTF(ttfPath);
20     }
21 
22     /**
23      * 从ttf文件创建Typeface对象
24      * 
25      * @ttfPath "fonts/XXX.ttf"
26      */
27     public Typeface getTypefaceFromTTF(String ttfPath) {
28 
29         if (ttfPath == null) {
30             return Typeface.DEFAULT;
31         } else {
32             return Typeface.createFromAsset(mContext.getAssets(), ttfPath);
33         }
34     }
35 
36     /**
37      * 设置TextView的字体 
38      * 
39      * @tv TextView对象
40      * @ttfPath ttf文件路径
41      * @isBold 是否加粗字体
42      */
43     public void setTypeface(TextView tv, boolean isBold) {
44         tv.setTypeface(mTypeface);
45         setBold(tv, isBold);
46     }
47 
48     /**
49      * 设置字体加粗
50      */
51     public void setBold(TextView tv, boolean isBold) {
52         TextPaint tp = tv.getPaint();
53         tp.setFakeBoldText(isBold);
54     }
55 
56     /**
57      * 设置TextView的字体为系统默认字体
58      * 
59      */
60     public void setDefaultTypeFace(TextView tv, boolean isBold) {
61         tv.setTypeface(Typeface.DEFAULT);
62         setBold(tv, isBold);
63     }
64 
65     /**
66      * 设置当前工具对象的字体
67      * 
68      */
69     public void setmTypeface(String ttfPath) {
70         mTypeface = getTypefaceFromTTF(ttfPath);
71     }
72 
73 }

  4、使用的时候只需这样调用:

1 TypefaceUtil tfUtil = new TypefaceUtil(mContext,"fonts/Jinglei.ttf");
2 tfUtil.setTypeface(tv,false);
原文地址:https://www.cnblogs.com/jiayongji/p/5516046.html