How To Show Alert Dialog In Android Using Xamarin
In this blog, you will learn how to show alert dialog (message) in Android applications, using Xamarin in Visual Studio 2015.
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.
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.
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent">
- <Button android:id="@+id/Button1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Simple Alert" />
- <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);
- <Button>(Resource.Id.Button1);
- button1.Click += Button_Click;
- Button button2 = FindViewById<Button>(Resource.Id.Button2);
- button2.Click += Button2_Click;
- }
- private void Button_Click(object sender, EventArgs e)
- {
- Android.App.AlertDialog.Builder dialog = new AlertDialog.Builder(this);
- AlertDialog alert = dialog.Create();
- alert.SetTitle("Title");
- alert.SetMessage("Simple Alert");
- alert.SetButton("OK", (c, ev) =>
- {
-
- });
- alert.Show();
- }
- private void Button2_Click(object sender, EventArgs e)
- {
- Android.App.AlertDialog.Builder dialog = new AlertDialog.Builder(this);
- AlertDialog alert = dialog.Create();
- alert.SetTitle("Title");
- alert.SetMessage("Complex Alert");
- alert.SetIcon(Resource.Drawable.alert);
- alert.SetButton("OK", (c, ev) =>
- {
-
- });
- alert.SetButton2("CANCEL", (c, ev) => { });
- alert.Show();
- }
We can set the alert box title and icon also.
Now, run the app and check that the output looks as shown below.