Tech
News
Videos
Forums
Jobs
Books
Events
More
Interviews
Live
Learn
Training
Career
Members
Blogs
Challenges
Certification
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Refer
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
How To Show Alert Dialog In Android Using Xamarin
WhatsApp
Suresh M
8y
148.8
k
0
1
25
Blog
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 A
ndroid 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);
// 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.
Android
Xamarin
Up Next
Xamarin Android: Create Android ProgressDialog App
Ebook Download
View all
Xamarin.Forms For Beginners
Read by 9.1k people
Download Now!
Learn
View all
Membership not found