簡單高效的實現Android App全局字體替換
Android O推出了一項新的功能「 Fonts in XML 」,借助這項功能,我們能夠像使用其他資源文件一樣使用字體,比較方便地實現App全局字體的替換。
為了能夠在API 14或者以上的設備上使用Fonts in XML特性,我們需要使用到Support Library 26。更多的內容可以參考「使用Support Library」小節。
在Android Studio中按照如下步驟將字體作為資源文件添加至工程:
-
右鍵單擊項目的 app / res 文件夾,然后選擇 New > Android resource directory 。
- 打開下拉菜單并選擇 font ,輸入 font 作為File name,點擊 OK 。
注意名稱字體資源文件夾的名稱必須為font
-
將字體文件拖放到新的 res / font 文件夾中。Android O支持 .otf(OpenType) 和 .ttf(TrueType) 兩種格式的字體文件。
-
雙擊字體文件可以在編輯器中對字體進行預覽。
創建Font family
在Android Studio中創建Font family的步驟如下:
-
右鍵單擊項目的 res / font 文件夾,然后選擇 New > Font resource file 。
-
輸入文件名,然后點擊 OK .
-
打開此XML文件并定義該字體的所有不同版本,以及其樣式和權重屬性,例如:
<?xml version="1.0" encoding="utf-8"?> <font-family xmlns:android="http://schemas.android.com/apk/res/android"> <font android:fontStyle="normal" android:fontWeight="400" android:font="@font/lobster_regular" /> <font android:fontStyle="italic" android:fontWeight="400" android:font="@font/lobster_italic" /> </font-family>
在XML布局中使用字體資源
給TextView添加字體
-
在XML布局文件中,將fontFamily設置為你想要的訪問的字體文件:
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:fontFamily="@font/lobster"/>
- 打開 Properties 窗口,設置TextView的字體:
- 選擇一種視圖打開 Properties 窗口
-
展開 textAppearance ,選擇fontFamily表中的一種字體類型。
添加字體至style
打開 style.xml 文件,將fontFamily屬性設置為你想要訪問的字體文件。
<style name="customfontstyle" parent="@android:style/TextAppearance.Small">
<item name="android:fontFamily">@font/lobster</item>
</style>
在你的App的Theme中配置此屬性即可實現整個App的字體替換。
使用代碼控制字體
Typeface typeface = getResources().getFont(R.font.myfont);
textView.setTypeface(typeface);
使用Support Library
當我們通過 Support Library 實現 Fonts in XML 特性時,需要使用 app 命名空間。Support Library目前支持API 14及以上。
在Android Support Library 26.0-beta1中,必須同時使用android和app命名空間進行聲明,以確保在Android O版本及以下設備上字體能夠被正確加載。
<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<font android:fontStyle="normal" android:fontWeight="400" android:font="@font/myfont-Regular"
app:fontStyle="normal" app:fontWeight="400" app:font="@font/myfont-Regular"/>
<font android:fontStyle="italic" android:fontWeight="400" android:font="@font/myfont-Italic"
app:fontStyle="italic" app:fontWeight="400" app:font="@font/myfont-Italic" />
</font-family>
通過代碼控制:
Typeface typeface = ResourcesCompat.getFont(context, R.font.myfont);
內容均來自Android Developer官網,做了簡單的翻譯,水平有限,還請見諒,原地址: https://developer.android.com/preview/features/fonts-in-xml.html
參考: https://developer.android.com/preview/features/working-with-fonts.html
更多內容:
-
油Tube - What's New in Android Support Library (Google I/O '17)
-
Google Developers Blog - Android O Developer Preview 終于推出啦!
- 知乎 - Android如何高效率的替換整個APP的字體?
另外,我在我的開源項目 TonnyL/PaperPlane 中使用 Fonts in XML 實現了App的字體的整體替換。效果如下:
來自:http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2017/0608/8049.html