天天看點

Android中使用自定義的字型

有時候應用中希望使用自定義的字型檔案,下面的代碼可以作為參考。

1. 将字型檔案放入assert檔案夾下,這裡為fonts/xxx.ttf。

2. 在需要改變字型的Acitivity中使用FontManager.changeFonts()方法來改變字型。

  1. package arui.blog.csdn.net;  
  2. import android.app.Activity;  
  3. import android.graphics.Typeface;  
  4. import android.view.View;  
  5. import android.view.ViewGroup;  
  6. import android.widget.Button;  
  7. import android.widget.EditText;  
  8. import android.widget.TextView;  
  9. public class FontManager {  
  10.     public static void changeFonts(ViewGroup root, Activity act) {  
  11.        Typeface tf = Typeface.createFromAsset(act.getAssets(),  
  12.               "fonts/xxx.ttf");  
  13.        for (int i = 0; i < root.getChildCount(); i++) {  
  14.            View v = root.getChildAt(i);  
  15.            if (v instanceof TextView) {  
  16.               ((TextView) v).setTypeface(tf);  
  17.            } else if (v instanceof Button) {  
  18.               ((Button) v).setTypeface(tf);  
  19.            } else if (v instanceof EditText) {  
  20.               ((EditText) v).setTypeface(tf);  
  21.            } else if (v instanceof ViewGroup) {  
  22.               changeFonts((ViewGroup) v, act);  
  23.            }  
  24.        }  
  25.     }  
  26. }