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

自定义TextView字体不生效求助:已创建自定义类及fonts文件夹

别急,我帮你一步步排查自定义TextView字体不生效的问题,大概率是这几个环节出了疏漏:

排查步骤

1. 字体文件的放置与命名是否正确

  • 确保字体文件(比如your_font.ttf/.otf)放在app/src/main/assets/fonts/目录下,注意assets文件夹需要手动创建(如果之前没建的话),不是res目录下的fonts文件夹哦!很多人会搞混这两个位置。
  • 字体文件名不能有空格、特殊字符,建议全小写加下划线,比如roboto_bold.ttf,避免系统识别失败。

2. 自定义TextView类的代码是否正确

检查你的自定义TextView类,有没有正确加载字体。举个正确的示例:
如果是Kotlin:

class CustomFontTextView(context: Context, attrs: AttributeSet) : AppCompatTextView(context, attrs) {
    init {
        // 加载字体,路径要和assets下的结构完全对应
        val typeface = Typeface.createFromAsset(context.assets, "fonts/your_font.ttf")
        setTypeface(typeface)
    }
}

如果是Java:

public class CustomFontTextView extends AppCompatTextView {
    public CustomFontTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        Typeface typeface = Typeface.createFromAsset(context.getAssets(), "fonts/your_font.ttf");
        setTypeface(typeface);
    }
}
  • 一定要继承AppCompatTextView而非原生TextView,避免兼容问题。
  • 路径字符串要和assets下的字体文件路径完全匹配,多一个少一个字符都不行。

3. 布局文件中是否正确引用了自定义TextView

检查你的activity_example_one.xml里的TextView标签,是不是用了完整的包名+类名,比如:

<com.yourpackage.name.CustomFontTextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="测试自定义字体"/>

如果只写CustomFontTextView,系统可能找不到这个自定义类,必须写全限定类名。

4. 有没有混淆导致字体加载失败

如果开启了混淆,需要在proguard-rules.pro里添加规则,避免字体文件被混淆压缩:

-keep class android.graphics.Typeface { *; }
-keepclassmembers class * {
    android.graphics.Typeface getTypeface();
}
-keepassets fonts/**

5. 清理缓存重新编译

有时候Android Studio的缓存会导致修改不生效,试试:

  • 点击菜单栏Build > Clean Project
  • 然后Build > Rebuild Project
  • 或者直接重启Android Studio

如果还是不行,可以把自定义TextView的完整代码和布局里的引用片段贴出来,我再帮你精准定位!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:37:29