Android自定义APP字体

发布时间 2023-09-06 21:30:12作者: 垃圾小熊猫

使用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设置字体之类的。这些方法都能用,但是实际测试少部分字体还行,全局使用的时候资源占用过高,还是推荐上列的第二种方法。