简体   繁体   English

如何在Xamarin表单Android中实现警报框

[英]How to implement an Alert box in xamarin forms android

I implemented a Dependency Service to display alert box in my xamarin forms app.My app crashes when I call the alert box in android. 我在Xamarin Forms应用程序中实现了一个依赖项服务来显示警报框。当我在android中调用警报框时,我的应用程序崩溃了。

Here is My code 这是我的代码

Android.App.AlertDialog.Builder _dialog = new AlertDialog.Builder(Android.App.Application.Context);
AlertDialog _alertDialog = _dialog.Create();
_alertDialog.SetTitle("Unauthorized");
_alertDialog.SetMessage("Please login again to continue using the      App);
_alertDialog.SetButton("OK", (c, ev) => { CloseApp(); });
_alertDialog.Show();

It throws an exception:-Unable to add window -- token null is not for an application in android. 它引发一个异常:-无法添加窗口-令牌null不适用于android中的应用程序。

How to fix this Please help me 如何解决这个问题,请帮帮我

Unable to add window -- token null is not valid; 无法添加窗口-令牌null无效; is your activity running? 您的活动正在进行吗?

You are using a Application context and you need to use an Activity based one. 您正在使用应用程序上下文,并且需要使用基于活动的上下文。

So you need the current Activity's context within your Forms' dependancy class which you can obtain that via multiple methods; 因此,您需要在Forms的依赖类中使用当前Activity的上下文,可以通过多种方法获取该上下文。 A static var on the MainActivity, using the "CurrentActivityPlugin", etc... MainActivity上的静态变量,使用“ CurrentActivityPlugin”等。

As a quick fix, add a static Context variable to your MainActivity class and set it in the OnResume override. 作为快速解决方案,将static Context变量添加到MainActivity类中,然后在OnResume重写中进行设置。

public static Context context;
protected override void OnResume()
{
    context = this;
    base.OnResume();
}

Then change your context to that static one: 然后将您的上下文更改为该静态上下文:

Android.App.AlertDialog.Builder _dialog = new Android.App.AlertDialog.Builder(MainActivity.context);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM