$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);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM