Android應用使用第三方字體

有時候爲了app的美觀可能會使用第三方字體,下面介紹幾種app使用第三方字體的方法。

第一種,通過反射全局設置app字體,這個方法簡單、粗暴、高效,推薦使用,下面介紹怎麼使用。

1、首先繼承application類並重寫oncreate方法

2、通過反射方式設置資源字體

[java] view plain copy
  1. public class App extends Application {  
  2.     public static Typeface typeFace;  
  3.   
  4.     @Override  
  5.     public void onCreate() {  
  6.         super.onCreate();  
  7.         //在app啓動創建時調用  
  8.         setTypeface();  
  9.     }  
  10.   
  11.     /** 
  12.      * 通過反射方法設置app全局字體 
  13.      */  
  14.     public void setTypeface(){  
  15.         typeFace = Typeface.createFromAsset(getAssets(), "fonts/aaa.ttf");  
  16.         try  
  17.         {  
  18.             Field field = Typeface.class.getDeclaredField("SERIF");  
  19.             field.setAccessible(true);  
  20.             field.set(null, typeFace);  
  21.         }  
  22.         catch (NoSuchFieldException e)  
  23.         {  
  24.             e.printStackTrace();  
  25.         }  
  26.         catch (IllegalAccessException e)  
  27.         {  
  28.             e.printStackTrace();  
  29.         }  
  30.     }  
  31. }  

3、在manifest文件中配置application和主題

4、主題中加入<itemname="Android:typeface">serif</item>



需要注意的的對於父主題的選擇上,不要使用android:Theme.DeviceDefault開始的主題,因爲這樣就反射設置的字體就無法生效。

第二種,單個設置textview,這樣比較的麻煩,textview有一個setTypeFace()方法,這樣就能改變字體樣式,這個方法不推薦使用。

第三種,比如說要所有的textview都要用第三方字體,那麼就重寫TextView,上面也說了textview有setTypeFace方法,將某人的字體替換成我們想要的就可以了。

[java] view plain copy
  1. public class CusFntTextView extends TextView {  
  2.    
  3. public CusFntTextView(Context context, AttributeSet attrs, int defStyle) {  
  4.     super(context, attrs, defStyle);  
  5.     init();  
  6. }  
  7.    
  8. public CusFntTextView(Context context, AttributeSet attrs) {  
  9.     super(context, attrs);  
  10.     init();  
  11. }  
  12.    
  13. public CusFntTextView(Context context) {  
  14.     super(context);  
  15.     init();  
  16. }  
  17.    
  18. private void init() {  
  19.     if (!isInEditMode()) {  
  20.         Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "Futura.ttf");  
  21.         setTypeface(tf);  
  22.     }  
  23. }  
第四種,github上有個開源的庫簡單的設置下就能使用字體,貼上介紹的帖子 點擊訪問

第五種,遍歷根節點,依次爲字控件設置字體,不推薦這樣使用,效率不高,浪費資源體驗也不好

最後貼上效果圖和demo的下載地址   點擊下載


發佈了343 篇原創文章 · 獲贊 120 · 訪問量 68萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章