Xamarin.Android

Dialogs

Remarks#

Setting the Context of the dialog

When creating a Dialog from an Activiy we can use this as the context.

AlertDialog.Builder builder = new AlertDialog.Builder(this);

With Fragments we use the property Context.

AlertDialog.Builder builder = new AlertDialog.Builder(Context);

Button types

SetNeutralButton() can be used for a simple notification and confirmation that the notification is read. SetPositiveButton() can be used for a confirmation for example: “Are you sure you want to delete this item?” SetNegativeButton() is for dismissing the dialog and cancelling it’s action.


Disable cancel from backbutton

If we want to make sure that the user can’t dismiss the dialog with the back button we can call SetCanceable(false). This only works for the back button.


Rotation

If the screen is rotated whilst a dialog is visible it will be dismissed and the ok and cancel actions will not be called. You will need to handle this inside your activity and re-show the dialog after the activity has been reloaded.

To get around this use a DialogFragment instead.

Alert dialog

Creating an alert dialog

AlertDialog.Builder builder = new AlertDialog.Builder(Context);
builder.SetIcon(Resource.Drawable.Icon);
builder.SetTitle(title);
builder.SetMessage(message);

builder.SetNeutralButton("Neutral", (evt, args) => { 
    // code here for handling the Neutral tap
});

builder.SetPositiveButton("Ok", (evt, args) => { 
    // code here for handling the OK tap
});

builder.SetNegativeButton("Cancel", (evt, args) => { 
    // code here for handling the Cancel tap
});

builder.SetCancelable(false);
builder.Show();

This modified text is an extract of the original Stack Overflow Documentation created by the contributors and released under CC BY-SA 3.0 This website is not affiliated with Stack Overflow