【发布时间】:2021-09-15 02:42:24
【问题描述】:
我有 xamarin.forms 应用程序。当用户在 android 的辅助功能设置中更改设备字体大小时,我的应用程序设计变得混乱。我可以防止。现在我面临的问题是,当用户再次更改 android 设置中的显示尺寸时,我的设计会被扭曲。我怎样才能防止这种情况?任何帮助表示赞赏。
【问题讨论】:
标签: xamarin xamarin.forms xamarin.android
我有 xamarin.forms 应用程序。当用户在 android 的辅助功能设置中更改设备字体大小时,我的应用程序设计变得混乱。我可以防止。现在我面临的问题是,当用户再次更改 android 设置中的显示尺寸时,我的设计会被扭曲。我怎样才能防止这种情况?任何帮助表示赞赏。
【问题讨论】:
标签: xamarin xamarin.forms xamarin.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);
}
【讨论】:
我想分享我对同一问题的解决方案,希望它对某人有所帮助。
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);
}
【讨论】: