Wednesday 9 January 2019

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.




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 <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) =>  
{  
// Ok button click task  
});  
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) =>  
{  
// Ok button click task  
});  
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.

No comments:

Post a Comment

All About .NET MAUI

  What’s .NET MAUI? .NET MAUI (.NET Multi-platform App UI) is a framework for building modern, multi-platform, natively compiled iOS, Androi...

Ads2