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

Xamarin.Forms如何获取系统字体大小 适配Android端RowHeight设置

可以在Xamarin主项目中获取Android平台的系统字体大小设置,实现仅针对Android平台动态适配RowHeight,具体实现方式如下:

实现步骤
  • 第一步:在共享项目定义跨平台服务接口
    用于抽象不同平台的系统字体缩放值获取逻辑:
    public interface IFontScaleService
    {
        float GetSystemFontScale();
    }
    
  • 第二步:在Android项目实现平台逻辑
    通过依赖注入注册服务,直接读取系统配置中的字体缩放参数:
    using Android.Content.Res;
    using Xamarin.Forms;
    
    [assembly: Dependency(typeof(FontScaleImplement))]
    namespace YourApp.Droid
    {
        public class FontScaleImplement : IFontScaleService
        {
            public float GetSystemFontScale()
            {
                // 系统默认字体缩放系数为1,字体调大时系数大于1,调小时系数小于1
                return Resources.System.Configuration.FontScale;
            }
        }
    }
    
  • 第三步:动态计算绑定的RowHeight属性值
    在对应页面的ViewModel中编写属性逻辑,仅在Android平台根据字体缩放系数调整行高:
    // 基础行高可根据业务需求自行定义
    private const double BaseRowHeight = 48;
    public double RowHeight
    {
        get
        {
            if (Device.RuntimePlatform == Device.Android)
            {
                var scale = DependencyService.Get<IFontScaleService>().GetSystemFontScale();
                return BaseRowHeight * scale;
            }
            return BaseRowHeight;
        }
    }
    

原有XAML代码无需修改,保持原有绑定写法即可:

<Grid.RowDefinitions>
    <RowDefinition Height="{Binding RowHeight}"></RowDefinition>
</Grid.RowDefinitions>

相关系统字体大小设置界面参考:
系统字体大小设置截图

补充:如果需要在App运行过程中实时响应用户修改系统字体大小的操作,可以在Android项目的MainActivity中重写OnConfigurationChanged方法,在配置变更时触发RowHeight的属性变更通知,即可实时刷新行高适配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 22:18:23