Xamarin.Android await AlertDialog.Builder

Programming xamarin_android C#

Sometimes you need to present the user with data and wait for a response while not locking up the UI thread.

Microsoft’s asynchronous programming model is our best friend and in just a few lines of code we can wait for a result from DialogBuilder. In this code example we’ll wait for AlertDialog’s positive or negative button being tapped.

bool result = await AlertAsync(this, "My Title", "My Message", "Yes", "No");

public Task<bool> AlertAsync(Context context, string title, string message, string positiveButtonTxt, string negativeButtonTxt)
var tcs = new TaskCompletionSource<bool>();

using (var db = new AlertDialog.Builder(context))
db.SetPositiveButton(positiveButtonTxt, (sender, args) => { tcs.TrySetResult(true); });
db.SetNegativeButton(negativeButtonTxt, (sender, args) => { tcs.TrySetResult(false); });

return tcs.Task;