1. 程式人生 > >Android開發中匯入字型庫

Android開發中匯入字型庫

摘要

  • 在Android開發中系統只提供了三種字型樣式,那麼如何使用自己想要的字型呢,使文字內容展示有更多的風格選擇呢?那就只能匯入外部字型庫,不過這種方式會導致apk體積暴增,有可能會讓你得不償失。聽說google釋出了新的字型庫,咱也來玩玩。

先上效果圖:

效果圖

基本用法步驟

  • 首先要將字型庫放入asset目錄下。
  • 使用方式:
        TextView tv_1=(TextView) findViewById(R.id.tv_1);
        TextView tv_2=(TextView) findViewById(R.id.tv_2);
        TextView tv_3=(TextView) findViewById(R.id
.tv_3); TextView tv_4=(TextView) findViewById(R.id.tv_4); TextView tv_5=(TextView) findViewById(R.id.tv_5); TextView tv_6=(TextView) findViewById(R.id.tv_6); TextView tv_7=(TextView) findViewById(R.id.tv_7); tv_1.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/SourceHanSansCN-Bold.otf"
)); tv_2.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/SourceHanSansCN-ExtraLight.otf")); tv_3.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/SourceHanSansCN-Heavy.otf")); tv_4.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/SourceHanSansCN-Light.otf"
)); tv_5.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/SourceHanSansCN-Medium.otf")); tv_6.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/SourceHanSansCN-Normal.otf")); tv_7.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/SourceHanSansCN-Regular.otf"));

進階用法步驟

  • 但是如果需要把整個App的字型都改變了,那這樣一個個更改豈不是太麻煩了?這時就需要全域性更改了。

步驟

  • 首先重寫Application,在onCreate()方法中執行下列程式碼:
 Typeface mTypeface = Typeface.createFromAsset(getAssets(), "fonts/NotoSansJP-Medium.otf");

        try {
            Field field = Typeface.class.getDeclaredField("MONOSPACE");
            field.setAccessible(true);
            field.set(null, mTypeface);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
  • 在style.xml檔案中自定義一個主題,讓重寫後的application使用這個主題;同時別忘了在清單檔案中宣告這個application。
  <style name="theme_fullScreen" parent="AppTheme">
        <item name="android:typeface">monospace</item>
 </style>
 <application
        android:name=".MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/theme_fullScreen">