[英]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.