有時候爲了app的美觀可能會使用第三方字體,下面介紹幾種app使用第三方字體的方法。
第一種,通過反射全局設置app字體,這個方法簡單、粗暴、高效,推薦使用,下面介紹怎麼使用。
1、首先繼承application類並重寫oncreate方法
2、通過反射方式設置資源字體
- public class App extends Application {
- public static Typeface typeFace;
- @Override
- public void onCreate() {
- super.onCreate();
- //在app啓動創建時調用
- setTypeface();
- }
- /**
- * 通過反射方法設置app全局字體
- */
- public void setTypeface(){
- typeFace = Typeface.createFromAsset(getAssets(), "fonts/aaa.ttf");
- try
- {
- Field field = Typeface.class.getDeclaredField("SERIF");
- field.setAccessible(true);
- field.set(null, typeFace);
- }
- catch (NoSuchFieldException e)
- {
- e.printStackTrace();
- }
- catch (IllegalAccessException e)
- {
- e.printStackTrace();
- }
- }
- }
3、在manifest文件中配置application和主題
4、主題中加入<itemname="Android:typeface">serif</item>
需要注意的的對於父主題的選擇上,不要使用android:Theme.DeviceDefault開始的主題,因爲這樣就反射設置的字體就無法生效。
第二種,單個設置textview,這樣比較的麻煩,textview有一個setTypeFace()方法,這樣就能改變字體樣式,這個方法不推薦使用。
第三種,比如說要所有的textview都要用第三方字體,那麼就重寫TextView,上面也說了textview有setTypeFace方法,將某人的字體替換成我們想要的就可以了。
- public class CusFntTextView extends TextView {
- public CusFntTextView(Context context, AttributeSet attrs, int defStyle) {
- super(context, attrs, defStyle);
- init();
- }
- public CusFntTextView(Context context, AttributeSet attrs) {
- super(context, attrs);
- init();
- }
- public CusFntTextView(Context context) {
- super(context);
- init();
- }
- private void init() {
- if (!isInEditMode()) {
- Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "Futura.ttf");
- setTypeface(tf);
- }
- }
第五種,遍歷根節點,依次爲字控件設置字體,不推薦這樣使用,效率不高,浪費資源體驗也不好
最後貼上效果圖和demo的下載地址 點擊下載