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

Android 33版本下如何禁用MAUI应用的系统字体缩放?

解决Android 33 MAUI应用禁用系统字体缩放问题

问题分析

你当前的实现存在两个核心问题:

  • 直接新建Configuration对象并调用SetToDefaults()会丢失原有屏幕配置(如屏幕方向、密度等),可能引发其他显示异常
  • 未处理系统配置变化事件(如用户中途修改系统字体缩放),导致后续界面仍会被系统缩放影响

正确实现方案

1. 重写Resources属性,基于当前配置修改字体缩放

不要创建全新的Configuration,而是复制当前配置并修改字体缩放参数,确保保留原有屏幕配置:

public override Android.Content.Res.Resources Resources
{
    get
    {
        Resources res = base.Resources;
        Configuration config = new Configuration(res.Configuration);
        
        // 强制设置字体缩放为1,禁用系统字体缩放
        config.FontScale = 1f;
        // 针对Android 13+,需要设置此参数确保字体缩放生效
        if (Build.VERSION.SdkInt >= BuildVersionCodes.Tiramisu)
        {
            config.FontWeightAdjustment = 0;
        }

        // 应用配置,避免创建重复的Resources对象
        if (Build.VERSION.SdkInt >= BuildVersionCodes.NMr1)
        {
            return CreateConfigurationContext(config).Resources;
        }
        else
        {
            res.UpdateConfiguration(config, res.DisplayMetrics);
            return res;
        }
    }
}

2. 处理系统配置变化事件

当用户修改系统字体缩放后,系统会触发配置变化回调,需在此时机重新锁定字体缩放:

public override void OnConfigurationChanged(Configuration newConfig)
{
    base.OnConfigurationChanged(newConfig);
    
    // 重新设置字体缩放为1
    Configuration config = new Configuration(newConfig);
    config.FontScale = 1f;
    if (Build.VERSION.SdkInt >= BuildVersionCodes.Tiramisu)
    {
        config.FontWeightAdjustment = 0;
    }

    if (Build.VERSION.SdkInt >= BuildVersionCodes.NMr1)
    {
        CreateConfigurationContext(config);
    }
    else
    {
        Resources.UpdateConfiguration(config, Resources.DisplayMetrics);
    }
    
    // 通知MAUI更新界面
    Microsoft.Maui.Controls.Application.Current?.OnConfigurationChanged(newConfig);
}

3. 额外配置:AndroidManifest.xml中声明配置变化

在Platforms/Android/AndroidManifest.xml的<activity>标签内添加以下属性,确保系统配置变化时不会重启Activity,而是触发OnConfigurationChanged:

android:configChanges="fontScale|orientation|screenSize|smallestScreenSize|screenLayout"

关键注意点

  • 不要使用SetToDefaults(),而是基于当前配置修改,避免丢失屏幕密度、方向等关键配置
  • Android 13(API 33)新增FontWeightAdjustment参数,需同时设置为0才能完全禁用字体缩放影响
  • 必须处理OnConfigurationChanged,否则用户中途修改系统字体缩放后,应用会再次被缩放

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 09:03:13