android 替换默认字体

本文介绍如何在Android应用中替换默认字体,包括sans、serif和monospace。通过将自定义的.ttf文件放置到assets/fonts目录,并利用FontUtils工具类进行字体替换。文中详细解释了在样式文件中设置字体及在Application类中调用方法完成替换的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

android默认字体(typeface)有三种:snas、serif、monospace,我们要做的就是替换掉其中一种或几种

1、将下载好的ttf文件放到 assets/fonts下


2、工具类FontUtils

 //设置新的字体样式
    public static void setDefaultFont(Context context, StringstaticTypefaceFieldName, String fontAssetName) {
        final Typeface regular =Typeface.createFromAsset(context.getAssets(),fontAssetName);
        replaceFont(staticTypefaceFieldName, regular);
    }
    
    //代替原来的文本样式
    protected static void replaceFont(String staticTypefaceFieldName, finalTypeface newTypeface) {
        
        Log.i("yyy",staticTypefaceFieldName+","+newTypeface.getStyle());
        try {
            final Field staticField =Typeface.class.getDeclaredField(staticTypefaceFieldName);
            staticField.setAccessible(true);
            staticField.set(null, newTypeface);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
3、下style中设置

<style name="AppTheme"parent="AppBaseTheme">
              <!-- All customizations that are NOT specific to a particularAPI-level can go here. -->
                <itemname="android:typeface">serif</item>
       </style>
      <application
         android:name="com.example.androidstudy.MyApplication"
         android:allowBackup="true"
          android:icon="@drawable/ic_launcher"
         android:label="@string/app_name"
         android:theme="@style/AppTheme" >...</application>

4、在Application中使用

 FontUtils.setDefaultFont(this, "SERIF","fonts/icomoon.ttf");
我们现在是替换的serif字体,sans好像是默认字体不能替换

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值