Resources.UpdateConfiguration已过时。

4

我想防止系统字体大小改变对我的Xamarin Forms Android应用程序产生影响。我尝试了下面在MainActivity.cs中的代码,它可以运行,但是告诉我已经过时(res.UpdateConfiguration)。我尝试了一些其他代码,但是没有成功。

public override Resources Resources
{
    get
    {
        Resources res = base.Resources;
        Configuration config = new Configuration();
        config.SetToDefaults();
        res.UpdateConfiguration(config, res.DisplayMetrics);
        return res;
    }

}

不行。 - D.madushanka
现在它能工作了吗? - Lucas Zhang
2个回答

6

context.getResources().updateConfiguration()已在Android API 25中被弃用,建议使用context.createConfigurationContext()代替。

public override Resources Resources
{
  get
  {              
   Configuration config = new Configuration();
   config.SetToDefaults();
               
   Context context = CreateConfigurationContext(config);
   Resources resources = context.Resources;

   return resources;
  }
}

请查看Android context.getResources.updateConfiguration()已被弃用

更新

如果您想更改字体大小,您应该重写方法AttachBaseContext

Java

protected override void AttachBaseContext(Context @base)
{
  // base.AttachBaseContext(@base);
  Configuration config = new Configuration();
  config.SetToDefaults();
  config.FontScale = 1.0f;
  Context context = @base.CreateConfigurationContext(config);
  base.AttachBaseContext(context);
}

Kotlin

override fun attachBaseContext(newBase: Context) {
    
    val config =  Configuration();
    config.setToDefaults();
    config.setLocale(Locale("mr"))
    
    super.attachBaseContext(newBase.createConfigurationContext(config));
}

我将这段代码放在MainActivity.cs中,但在更改系统字体大小后界面没有任何变化。 - D.madushanka
仍然无法工作。我正在我的小米mi4c Android 7手机上进行测试。我认为 DisplayMetrics 有所不同。在过时的版本中,它具有 DisplayMetrics - D.madushanka
它正在工作。我犯了一个错误。我在 API 24 手机上两次检查过了。那就是问题所在。谢谢。 - D.madushanka
我遇到了 Configuration is a namespace but is used like a type 错误。 - Oiproks
对于Java,大多数方法都是小写的,如果您在复制粘贴后遇到错误,可以考虑这一点:
  • attachBaseContext
  • setToDefaults
  • config.fontScale
  • base.createConfigurationContext
- FrankKrumnow
我们把这段代码放在哪里? - undefined

1
如果您不喜欢使用protected override,您可以使用
private void initFontScale()
{
     Configuration configuration = Resources.Configuration;
     configuration.FontScale = (float)1.45;
     //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.ApplicationContext.CreateConfigurationContext(configuration); BaseContext.Resources.DisplayMetrics.SetTo(metrics);
}

protected override void OnCreate(Bundle bundle)
{
    initFontScale();
    ...
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接