防止显示大小更改设置影响应用程序设计 - Xamarin.forms

问题描述

我有 xamarin.forms 应用程序。当用户在 android 的辅助功能设置中更改设备字体大小时,我的应用程序设计会变得混乱。我能够阻止。现在我面临的问题是当用户再次更改 android 设置中的显示大小时,我的设计会失真。我怎样才能防止这种情况?任何帮助表示赞赏。

解决方法

我有 xamarin.forms 应用程序。当用户在 android 的辅助功能设置中更改设备字体大小时,我的应用程序设计会变得混乱。我能够阻止。现在我面临的问题是当用户再次更改 android 设置中的显示大小时,我的设计会失真。我怎样才能防止这种情况?任何帮助表示赞赏。

您可以在 Mainactivity.cs 中尝试以下代码:

   private void initFontScale()
    {
        Configuration configuration = Resources.Configuration;
        configuration.FontScale = (float)1;
        //0.85 small,1 standard,1.15 big,1.3 more bigger ,1.45 supper big 
        DisplayMetrics metrics = new DisplayMetrics();
        WindowManager.DefaultDisplay.GetMetrics(metrics);
        metrics.ScaledDensity = configuration.FontScale * metrics.Density;
        //BaseContext.Resources.UpdateConfiguration(configuration,metrics);
        BaseContext.ApplicationContext.CreateConfigurationContext(configuration); 
        BaseContext.Resources.DisplayMetrics.SetTo(metrics);
    }

protected override void OnCreate(Bundle savedInstanceState)
    {
        initFontScale();
        TabLayoutResource = Resource.Layout.Tabbar;
        ToolbarResource = Resource.Layout.Toolbar;
        
        base.OnCreate(savedInstanceState);
        ...
        LoadApplication(new App());
    }

您也可以尝试覆盖 attachBaseContext 方法:

        protected override void AttachBaseContext(Context @base)
    {
        Configuration overrideConfiguration = new Configuration();
        overrideConfiguration = @base.Resources.Configuration;
        overrideConfiguration.SetToDefaults();
        var fontScale = overrideConfiguration.FontScale;
        overrideConfiguration.FontScale = (float)1;
        Context context = @base.CreateConfigurationContext(overrideConfiguration);
        base.AttachBaseContext(context);
    }