You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android原生自定义字体布局生效,代码动态添加TextView时失效求助

解决Android动态添加TextView时自定义Native Fonts不生效的问题

我之前也碰到过一模一样的问题,布局里的TextView能正常加载自定义字体,但动态创建的就不行,其实是动态设置Typeface的方式不对,咱们一步步来修复:

第一步:先确认字体族资源配置正确

首先检查你在res/font/目录下创建的字体族XML(比如my_font_family.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/my_font" />
    <!-- 斜体样式字体 -->
    <font
        android:fontStyle="italic"
        android:fontWeight="400"
        android:font="@font/my_font_italic" />
</font-family>

同时确保字体文件名是全小写(Android资源文件名不支持大写或特殊字符,下划线没问题),且确实放在res/font/目录下。

第二步:动态创建TextView时用正确方式获取Typeface

你之前尝试的Typeface typeface = R...的方式肯定不对,因为R.font.xxx是资源ID,不能直接赋值给Typeface对象。正确的做法是用ResourcesCompat来获取字体,它能兼容所有Android版本:

Kotlin示例

// 获取字体族(自动匹配样式)
val fontFamily = ResourcesCompat.getFont(context, R.font.my_font_family)
// 或者直接获取单个字体(比如斜体)
val italicFont = ResourcesCompat.getFont(context, R.font.my_font_italic)

// 动态创建TextView并设置字体
val dynamicTextView = TextView(context).apply {
    text = "这是动态添加的文本"
    // 设置字体族,后续设置textStyle会自动匹配对应字体
    typeface = fontFamily
    // 如果要直接用斜体,也可以这样:
    // typeface = italicFont
    // 或者通过textStyle指定斜体(需要字体族包含对应样式)
    // setTypeface(fontFamily, Typeface.ITALIC)
}

// 添加到LinearLayout
yourLinearLayout.addView(dynamicTextView)

Java示例

// 获取字体族
Typeface fontFamily = ResourcesCompat.getFont(context, R.font.my_font_family);
// 获取斜体字体
Typeface italicFont = ResourcesCompat.getFont(context, R.font.my_font_italic);

// 动态创建TextView
TextView dynamicTextView = new TextView(context);
dynamicTextView.setText("这是动态添加的文本");
// 设置字体族
dynamicTextView.setTypeface(fontFamily);
// 或者设置斜体样式
// dynamicTextView.setTypeface(fontFamily, Typeface.ITALIC);

// 添加到LinearLayout
yourLinearLayout.addView(dynamicTextView);

容易踩的坑提醒

  • 不要用Typeface.create("my_font", Typeface.NORMAL)这种方式,它是通过字体名称加载系统字体,无法识别你的自定义Native Fonts。
  • 如果你想通过样式来统一设置字体,可以创建一个TextAppearance样式,然后给动态TextView设置:
    <!-- res/values/styles.xml -->
    <style name="CustomTextStyle">
        <item name="android:fontFamily">@font/my_font_family</item>
        <item name="android:textSize">16sp</item>
        <item name="android:textStyle">italic</item>
    </style>
    
    代码中设置:
    dynamicTextView.setTextAppearance(R.style.CustomTextStyle)
    

内容的提问来源于stack exchange,提问作者roy_lennon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:57:13