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

Prevent display size change settings affect app design - Xamarin.forms

我有 xamarin.forms 应用程序。当用户在 android 的辅助功能设置中更改设备字体大小时,我的应用程序设计被打乱了。我能够 prevent.Now 我面临的问题是,当用户在 android 的设置中再次更改显示大小时,我的设计又被扭曲了。我怎样才能防止这种情况发生?感谢任何帮助。

I have xamarin.forms app. When user change the device font size in accessibility settings of android, My apps design gets scrampled. Which I am able to prevent.Now the problem I am facing is when user change the display size in the settings of android again my design gets distorted. How can I prevent this? Any help is appreciated.

您可以在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);
    }

我想分享我对同样问题的解决方案,希望它能对某人有所帮助。

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);
  
  //I added the next lines to keep the density.
  
  metrics.Density = configuration.FontScale * (DisplayMetrics.DensityDeviceStable / 160 f);
  metrics.ScaledDensity = metrics.Density;
  configuration.DensityDpi = (int) DisplayMetrics.DensityDeviceStable;
  metrics.DensityDpi = (DisplayMetricsDensity) DisplayMetrics.DensityDeviceStable;
  
  BaseContext.ApplicationContext.CreateConfigurationContext(configuration);
  BaseContext.Resources.DisplayMetrics.SetTo(metrics);

}