【问题标题】:Xamarin: Obsolete Forms.Context and AlertDialog.BuilderXamarin:过时的 Forms.Context 和 AlertDialog.Builder
【发布时间】:2018-05-19 06:48:32
【问题描述】:

我以前是这样创建的

        AlertDialog.Builder b = new AlertDialog.Builder( Forms.Context );

而且效果很好。但是 Forms.Context 现在已经过时了,所以我把它改成了

        AlertDialog.Builder b = new AlertDialog.Builder( Android.App.Application.Context );

现在它崩溃了

Android.Content.Res.Resources+NotFoundException: Resource ID #0x0

我尝试了替代构造函数

        AlertDialog.Builder b = new AlertDialog.Builder( Android.App.Application.Context, Resource.Style.Theme_AppCompat_Light );

然后崩溃了

Android.Views.WindowManagerBadTokenException: Unable to add window -- token null is not for an application

那么我在 XF2.5 中将什么上下文传递给 AlertDialog.Builder()?我不想为此安装第 3 方库。

【问题讨论】:

  • 尝试传入你的 MainActivity

标签: xamarin xamarin.forms android-alertdialog android-context


【解决方案1】:

一种方法是像这样在 Main Activity 中创建一个静态变量

public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
    internal static MainActivity Instance { get; private set; }

    protected override void OnCreate(Bundle bundle)
    {
        ...
        global::Xamarin.Forms.Forms.Init(this, bundle);
        Instance = this;
        LoadApplication(new App());
    }
}

像这样在你的代码中引用它

AlertDialog.Builder b = new AlertDialog.Builder( MainActivity.Instance );

如需了解更多详情和其他实现方式,see David Britchs blog post

【讨论】:

  • 链接中的引用:“Xamarin.Forms.Forms.Context 已被标记为过时,因为它是对 Activity 的全局静态引用,这并不理想。”那么用另一个全局静态替换一个全局静态有什么好处呢?
  • @AntonDuzenko XF 这样做是因为使用旧方法,您无法确定上下文是否来自 MainActivity。使用这种方法,当您要使用 Instance 时,请指定 MainActivity.Instance。例如,您的目标似乎是 MainActivity 而不是 SplashscreenActivity。你可以在这里找到更多:stackoverflow.com/questions/47353986/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-07
  • 2011-10-13
  • 1970-01-01
  • 2011-11-03
相关资源
最近更新 更多