Confirmation Dialog on back button press event Xamarin.Forms

后端 未结 6 825
北海茫月
北海茫月 2020-12-14 19:16

I am stuck at one point in Xamarin.Forms application

On Back button press simply I want to ask user to confirm whether he really wants to exit or not, \"OnBackButton

6条回答
  •  我在风中等你
    2020-12-14 19:53

    public override void OnBackPressed()
    {
        RunOnUiThread(
            async () =>
            {
                var isCloseApp = await AlertAsync(this, "NameOfApp", "Do you want to close this app?", "Yes", "No");
    
                if (isCloseApp)
                {
                    var activity = (Activity)Forms.Context;
                    activity.FinishAffinity();
                }
            });
    }
    
    public Task AlertAsync(Context context, string title, string message, string positiveButton, string negativeButton)
    {
        var tcs = new TaskCompletionSource();
    
        using (var db = new AlertDialog.Builder(context))
        {
            db.SetTitle(title);
            db.SetMessage(message);
            db.SetPositiveButton(positiveButton, (sender, args) => { tcs.TrySetResult(true); });
            db.SetNegativeButton(negativeButton, (sender, args) => { tcs.TrySetResult(false); });
            db.Show();
        }
    
        return tcs.Task;
    }
    

    Xamarin.Android await AlertDialog.Builder

提交回复
热议问题