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

Xamarin Forms Android切换AppShell时提示找不到sans-serif-medium字体

解决Xamarin Forms Android端切换到Shell时的字体异常问题

针对Android端调用SwitchToShell切换到Shell时抛出Java.Lang.RuntimeException: Font asset not found sans-serif-medium的问题,可通过以下几种方案解决:

方案1:替换Shell的系统字体依赖

Android部分版本可能缺少sans-serif-medium字体,直接在Shell的全局样式中指定存在的系统字体替代:

<Shell.Resources>
    <ResourceDictionary>
        <!-- 为所有Label设置基础sans-serif字体 -->
        <Style TargetType="Label">
            <Setter Property="FontFamily" Value="sans-serif" />
        </Style>
        <!-- 为Shell的菜单项单独设置字体 -->
        <Style TargetType="MenuItem">
            <Setter Property="FontFamily" Value="sans-serif" />
        </Style>
    </ResourceDictionary>
</Shell.Resources>

方案2:确保切换操作在主线程执行

动态切换页面时,必须保证UI操作在Android主线程完成,避免资源加载时机异常:

public async void SwitchToShell()
{
    await MainThread.InvokeOnMainThreadAsync(() =>
    {
        MainPage = new AppShell();
    });
}

方案3:修正Android项目的主题字体配置

检查Android项目Resources/values/styles.xml中的主题设置,移除对sans-serif-medium的硬编码:

<style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar">
    <!-- 替换为系统存在的字体 -->
    <item name="android:fontFamily">sans-serif</item>
</style>

方案4:嵌入自定义字体彻底规避系统字体问题

如果系统字体依赖问题无法彻底解决,直接嵌入自定义字体:

  1. 将字体文件(如Roboto-Medium.ttf)放入Android项目的Assets文件夹,设置生成操作为AndroidAsset
  2. 在App.xaml.cs构造函数中注册字体:
    FontImageSource.RegisterFont("Roboto-Medium.ttf");
    
  3. 在Shell样式中指定自定义字体:
    <Style TargetType="Label">
        <Setter Property="FontFamily" Value="Roboto-Medium.ttf#Roboto Medium" />
    </Style>
    

问题原因说明

启动时直接进入Shell,App初始化流程会完整触发Android资源系统的字体加载;而动态切换Shell时,Shell是在后续时机创建,部分系统字体的引用未被正确初始化,导致找不到sans-serif-medium资源。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 19:05:18