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

Android开发新手求助:自定义字体在Type.kt中无法初始化

解决Jetpack Compose中自定义Montserrat字体未解析引用的问题
  • 确认资源目录与命名规范
    确保font目录严格建在res文件夹下(路径:src/main/res/font/),字体文件名必须遵循Android资源命名规则:仅使用小写字母、数字、下划线,比如montserrat_regular.ttf、montserrat_bold.ttf,不能出现大写或特殊字符。

  • 生成字体族XML文件
    Lint提示生成XML是因为Compose推荐通过字体族XML统一管理同系列字体。在res/font/下新建XML文件(例如montserrat.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/montserrat_regular" />
        <font
            android:fontStyle="normal"
            android:fontWeight="700"
            android:font="@font/montserrat_bold" />
    </font-family>
    

    注意android:font中的文件名要和你实际的字体文件完全一致。

  • 在Type.kt中正确初始化字体
    同步项目后,在Type.kt中通过以下方式定义字体变量:
    如果你使用较新版本Compose:

    import androidx.compose.ui.text.font.FontFamily
    import androidx.compose.ui.res.fontFamilyResource
    import com.yourpackage.name.R
    
    val Montserrat = fontFamilyResource(R.font.montserrat)
    

    旧版本Compose可手动构建FontFamily:

    import androidx.compose.ui.text.font.Font
    import androidx.compose.ui.text.font.FontFamily
    import androidx.compose.ui.text.font.FontWeight
    import com.yourpackage.name.R
    
    val Montserrat = FontFamily(
        Font(R.font.montserrat_regular, FontWeight.Normal),
        Font(R.font.montserrat_bold, FontWeight.Bold)
    )
    
  • 同步与验证
    点击Android Studio工具栏的「Sync Project with Gradle Files」按钮,完成同步后错误应该消失。之后就可以在Compose文本组件中使用:

    Text(
        text = "测试内容",
        fontFamily = Montserrat,
        fontWeight = FontWeight.Bold
    )
    
  • 常见排查点

    • 检查字体文件名与XML中的引用是否完全匹配(Android资源识别大小写敏感)
    • 确认res/font目录被标记为资源根目录(右键目录→「Mark Directory as」→「Resources Root」)
    • 清理缓存:点击「File」→「Invalidate Caches...」→「Invalidate and Restart」,解决缓存导致的资源不识别问题

内容的提问来源于stack exchange,提问作者mw.98

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 23:05:17