Displaying alert dialog in Android using Xamarin

Alert dialog is a important part of any application. Conveying various information, error messages and even for taking confirmations from user can be done through alert dialog. Xamarin provides it’s own way of showing alert and conveying messages to the user.

Alerts in Xamarin are, an object of AlertDialog.Builder class, where AlertDialog is a subclass of Dialog class. Builder() is a method of AlertDialog class, which creates an alert dialog to display. We can add multiple buttons to this alert dialog. The builder takes the current context (Activity) and shows the Alert Box in the main thread(The UI thread).

Below is a code for demonstrating the same.


//set alert for executing the task
AlertDialog.Builder alert = new AlertDialog.Builder (this);

alert.SetTitle ("Hi, how are you");

alert.SetPositiveButton ("Good", (senderAlert, args) => {
	//change value write your own set of instructions
	//you can also create an event for the same in xamarin
	//instead of writing things here
} );

alert.SetNegativeButton ("Not doing great", (senderAlert, args) => {
	//perform your own task for this conditional button click
} );
//run the alert in UI thread to display in the screen
RunOnUiThread (() => {
} );

Using the AlertDialog class, we can show an alert with up to three buttons. Also we can apply our own layout inside the alert using this.

Written By: Anobik Dey, Software Developer, Mindfire Solutions

2 thoughts on “Displaying alert dialog in Android using Xamarin

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s