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

如何解决Android Studio中字体文件名与内部名称不匹配问题?

解决Android字体文件名小写与布局引用冲突问题

方案1:创建字体资源映射XML(推荐)

这种方式能同时满足系统文件名小写要求,以及让布局引用和构建流程都正常工作:

  1. 在res/font目录下新建一个小写文件名的XML文件,比如bauhausregular.xml
  2. 在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="300"
        android:font="@font/bauhausregular" /> <!-- 此处对应你的小写字体文件名 -->
</font-family>
  1. 布局中直接引用这个XML资源:
<TextView
    android:id="@+id/textView"
    android:layout_marginTop="10dp"
    android:textSize="12sp" <!-- 注意:文字大小建议用sp单位而非dp -->
    android:font="@font/bauhausregular"
    android:textFontWeight="300"/>

方案2:代码动态设置字体+tools属性预览

如果想保留设计视图的驼峰名预览效果,同时避免构建报错:

  1. 布局中使用tools:前缀的属性仅用于设计视图预览,不设置android:字体属性:
<TextView
    android:id="@+id/textView"
    android:layout_marginTop="10dp"
    android:textSize="12sp"
    tools:font="@font/BauhausRegular" <!-- 仅设计视图生效 -->
    android:textFontWeight="300"/>
  1. 在Activity/Fragment中通过代码加载字体:

Kotlin

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    
    val textView = findViewById<TextView>(R.id.textView)
    textView.typeface = ResourcesCompat.getFont(this, R.font.bauhausregular)
}

Java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    
    TextView textView = findViewById(R.id.textView);
    textView.setTypeface(ResourcesCompat.getFont(this, R.font.bauhausregular));
}

这样设计视图能正常显示字体效果,构建时通过代码加载正确的小写资源文件,不会报错。

方案3:清理Android Studio缓存

有时候设计视图不识别小写引用是缓存问题,尝试清理缓存:

  • 点击顶部菜单栏 File > Invalidate Caches...
  • 选择 Invalidate and Restart,重启后再尝试在布局中用@font/bauhausregular引用,看设计视图是否能正常识别。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 20:55:19