搬砖日记

搬砖日记

Android自定義APP字型

使用 Android 设备自帶的字體時:#

<!--在你的APP主題或者需要用到的地方的主題中設置樣式-->
<style name="CustomStyle" parent="AppBaseTheme">
    <item name="android:textViewStyle">@style/CustomFontStyleText</item>
    <item name="android:buttonStyle">@style/CustomFontStyleButton</item>
</style>

<!--在需要設置的控件中設置字體樣式-->
<style name="CustomFontStyleText" parent="android:Widget.TextView">
    <item name="android:fontFamily">你的字體名字</item>
</style>
<style name="CustomFontStyleButton" parent="android:Widget.Holo.Button">
    <item name="android:fontFamily">你的字體名字</item>
</style>

注意,當你的主題的父主題是 AppCompat 的主題,如 Theme.AppCompat.Light.DarkActionBar 時,在設置 android:fontFamily 的時候需要去掉android: ,也就是將上面的第二行替換為:

<item name="android:fontFamily">CustomStyle</item>

然後在 Manifest 文件中設置主題即可

<!--如果你設置成application的主題的話-->
<application
    android:theme="@style/AppTheme" >
</application>

使用自定義字體時:#

很多時候,你的用戶的運行環境並不統一,這就需要你在開發時提前放進自己需要的字體。放字體具體的位置:在你的資源文件夾內,創建 font 文件夾即可。

使用方式:

<style name="CustomStyle" parent="Theme.AppCompat.Light.NoActionBar">
   <item name="android:fontFamily">@font/你的字體</item>
   <item name="fontFamily">@font/你的字體</item>
</style>

然後在 Manifest 文件中設置主題即可

<!--如果你設置成application的主題的話-->
<application
    android:theme="@style/AppTheme" >
</application>

注意:
支持庫 26.0 支持在搭載 Android 4.1(API 級別 16)及更高版本的設備上使用 “XML 中的字體” 功能。更多的自定義的使用方法你可以參考官方文檔:https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml


以上就是更換字體的一些方法。網上還有很多方法,例如遍歷控件,設置字體;自定義 view 設置字體之類的。這些方法都能用,但是實際測試少部分字體還行,全局使用的時候資源佔用過高,還是推薦上列的第二種方法。

載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。