[英]How to implement an Alert box in xamarin forms android
我在Xamarin Forms应用程序中实现了一个依赖项服务来显示警报框。当我在android中调用警报框时,我的应用程序崩溃了。
这是我的代码
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();
它引发一个异常:-无法添加窗口-令牌null不适用于android中的应用程序。
如何解决这个问题,请帮帮我
无法添加窗口-令牌null无效; 您的活动正在进行吗?
您正在使用应用程序上下文,并且需要使用基于活动的上下文。
因此,您需要在Forms的依赖类中使用当前Activity的上下文,可以通过多种方法获取该上下文。 MainActivity上的静态变量,使用“ CurrentActivityPlugin”等。
作为快速解决方案,将static
Context变量添加到MainActivity
类中,然后在OnResume
重写中进行设置。
public static Context context;
protected override void OnResume()
{
context = this;
base.OnResume();
}
然后将您的上下文更改为该静态上下文:
Android.App.AlertDialog.Builder _dialog = new Android.App.AlertDialog.Builder(MainActivity.context);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.