1. 程式人生 > >Android中字型設定和calligraphy(高效載入字型包)用法

Android中字型設定和calligraphy(高效載入字型包)用法

Android預設字型

TextView 的 typeface 屬性支援 “Sans”,”serif”,”monospace” 這三種字型,如果在沒有指定字型的情況下,系統預設會使用 “Sans” 作為文字顯示的字型。但這三種字型只支援英文,也就是說只要你顯示的文字是中文,無論你選擇這三種字型中的哪一種,顯示效果都是一樣的

xml

<!--  使用預設的sans字型-->
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
android:id="@+id/sans" android:text="Hello,World" android:typeface="sans" android:textSize="20sp" />
<!-- 使用預設的serifs字型--> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
android:id="@+id/serif" android:text="Hello,World" android:typeface="serif" android:textSize="20sp" />
<!-- 使用預設的monospace字型--> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
android:id="@+id/monospace" android:text="Hello,World" android:typeface="monospace" android:textSize="20sp" />

效果

這裡寫圖片描述

Android中可以引入其他字型

首先要將字型檔案儲存在assets/fonts/目錄下

關鍵程式碼

Typeface typeFace =Typeface.createFromAsset(getAssets(),"fonts/default.ttf");
textView.setTypeface(typeFace);

calligraphy(高效載入字型包)

1、新增依賴

compile ‘uk.co.chrisjenx:calligraphy:2.3.0’

2、新增字型

這裡寫圖片描述

3、安裝

在自己定義的Appliction類中的OnCreate方法中新增如下語句

@Override
public void onCreate() {
    super.onCreate();
    CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
                            .setDefaultFontPath("fonts/Roboto-RobotoRegular.ttf")
                            .setFontAttrId(R.attr.fontPath)
                            .build()
            );
    //....
}

4、定義一個BaseActivity類,所有的Activity都繼承該類,然後新增如下方法(複寫的)

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
    }

5、用法

   <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView2"
        android:text="Hello,World"
        android:textSize="20sp"
        fontPath="fonts/default.ttf"/>