How To Show Alert Dialog In Android Using Xamarin

We will see two types of alerts in this article. Simple alert, which has a message, title, and single button; and a complex alert, which will have a title and  message with two buttons.

Let’s see the steps

Create a new Android project and it looks as shown below.

android

Now, go to your Main.axml page and add two buttons, where one is to show simple alert and another is for showing complex alert, using the code given below.
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent">  
  2.     <Button android:id="@+id/Button1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Simple Alert" />  
  3.     <Button android:id="@+id/Button2" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Complex Alert" /> </LinearLayout> Now go to MainActivity.cs file and write the below code to show alert. Get the button properties and subscribe the button click event. protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); Button button1 = FindViewById  
  4. <Button>(Resource.Id.Button1);  
  5. button1.Click += Button_Click;  
  6. Button button2 = FindViewById<Button>(Resource.Id.Button2);  
  7. button2.Click += Button2_Click;  
  8. }  
  9. private void Button_Click(object sender, EventArgs e)  
  10. {  
  11. Android.App.AlertDialog.Builder dialog = new AlertDialog.Builder(this);  
  12. AlertDialog alert = dialog.Create();  
  13. alert.SetTitle("Title");  
  14. alert.SetMessage("Simple Alert");  
  15. alert.SetButton("OK", (c, ev) =>  
  16. {  
  17. // Ok button click task  
  18. });  
  19. alert.Show();  
  20. }  
  21. private void Button2_Click(object sender, EventArgs e)  
  22. {  
  23. Android.App.AlertDialog.Builder dialog = new AlertDialog.Builder(this);  
  24. AlertDialog alert = dialog.Create();  
  25. alert.SetTitle("Title");  
  26. alert.SetMessage("Complex Alert");  
  27. alert.SetIcon(Resource.Drawable.alert);  
  28. alert.SetButton("OK", (c, ev) =>  
  29. {  
  30. // Ok button click task  
  31. });  
  32. alert.SetButton2("CANCEL", (c, ev) => { });  
  33. alert.Show();  
  34. }  
We can set the alert box title and icon also.

Now, run the app and check that the output looks as shown below.

android

android

android
X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now