2016-10-07 64 views
1

是新的Android開發我需要爲整個應用程序自定義字體爲我寫了:如何更改棒棒糖版本以上的Android應用程序的默認字體?

public class TypeFaceUtil { 
    public static void overrideFont(Context context, String defaultFontNameToOverride, String customFontFileNameInAssets) { 
     final Typeface customFontTypeface = Typeface.createFromAsset(context.getAssets(), customFontFileNameInAssets); 
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { 
      Map<String, Typeface> newMap = new HashMap<String, Typeface>(); 
      newMap.put("SERIF", customFontTypeface); 
      try { 
       final Field staticField = Typeface.class 
         .getDeclaredField("sSystemFontMap"); 
       staticField.setAccessible(true); 
       staticField.set(null, newMap); 
      } catch (NoSuchFieldException e) { 
       e.printStackTrace(); 
      } catch (IllegalAccessException e) { 
       e.printStackTrace(); 
      } 
     } else { 
      try { 
       final Field defaultFontTypefaceField = Typeface.class.getDeclaredField(defaultFontNameToOverride); 
       defaultFontTypefaceField.setAccessible(true); 
       defaultFontTypefaceField.set(null, customFontTypeface); 
      } catch (Exception e) { 
       Log.e(TypeFaceUtil.class.getSimpleName(), "Can not set custom font " + customFontFileNameInAssets + " instead of " + defaultFontNameToOverride); 
      } 
     } 
    } 
} 

,我把它叫做應用程序類是這樣的:

public class tt extends Application { 

    @Override 
    public void onCreate() { 
     super.onCreate(); 
     TypeFaceUtil.overrideFont(getApplicationContext(),"SERIF","fonts/calibri.ttf"); 
    } 
} 

我的字體是不在棒棒糖或以上版本工作,我也嘗試這種方法Custom Fonts not working in lollipop?如何創建一個支持所有版本的自定義字體提前謝謝

+0

除非通過調用textview,button或其他視圖的setTypeface()方法來設置字體,否則字體將不會「工作」。 – Talha

+0

@ M.Yogeshwaran看到我的回答 –

回答

0

終於讓我找到這樣的解決方案我喜歡分享我的解決方案,以便將來學習我已經覆蓋了value-21文件中的默認字體,需要刪除主題中的字體項以便使用自定義字體。

0

添加此庫編譯'me.anwarshahriar:calligrapher:1.0'

,並在代碼裏你的onCreate

Calligrapher calligrapher = new Calligrapher(this); 
calligrapher.setFont(this, "fonts/calibri.ttf", true); 
+0

它可以在應用程序類中使用 –