Introduction
In this article, I am going to demonstrate using AlertDialog, which is used to display
custom message to user and it’s highly extensible. Generally you are allowed to
set upto three button with custom text and there handler as usual, as everything in Android
is asynchronous.
This article is divided into three parts namely
- Original AlertBox - Normal way of using alertdialog
- AlertBox with ListView - AlertDialog containing listview
- AlertBox with custom layout - AlertDialog contain custom layout.
AlertBox is one is most widely use control in android world. It's everywhere.I daily encounter it while playing game on my wife mobile, asking “do you want to Quit”.
Step By Step we move forward
- Create Android application by selecting New ->Solutions and
provide its name “AndroidAlertDialogDemo”
- Once Project is created, Open Resource Folder->Layout and edit
Main.Axml layout file. we going to add three button in this, Once modified code
looks like this:-
="1.0"="utf-8"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="@+id/myButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Base AlertBox" />
<Button
android:id="@+id/myButton1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="AlertBox with ListView" />
<Button
android:id="@+id/myButton2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="AlertBox with CustomView" />
</LinearLayout>
Here what I have done, I have added relative layout and added three button inside
it, one each for each part of article
- Now, open MainActivity.cs file, find the
button1
object and add click event handler
for invoking base AlertDialog from it.
Button btnNormalDialog = FindViewById<Button> (Resource.Id.myButton);
btnNormalDialog.Click += methodInvokeBaseAlertDialog;
- Now in click handler, setup the AlertDialog invocation code, have a look at code
first:-
void methodInvokeBaseAlertDialog (object sender, EventArgs e)
{
var dlgAlert = (new AlertDialog.Builder (this)).Create ();
dlgAlert.SetMessage ("Hello from alertDialog");
dlgAlert.SetTitle ("Alert Dialog");
dlgAlert.SetButton ("OK", handllerNotingButton);
dlgAlert.SetButton2 ("Cancel", handllerNotingButton);
dlgAlert.SetButton3 ("Nothing", handllerNotingButton);
dlgAlert.Show ();
}
void handllerNotingButton (object sender, DialogClickEventArgs e)
{
AlertDialog objAlertDialog = sender as AlertDialog;
Button btnClicked = objAlertDialog.GetButton (e.Which);
Toast.MakeText (this, "you clicked on " + btnClicked.Text, ToastLength.Long).Show ();
}
We are doing following:-
- Use (AlertDialog.Builder(this)) static method create AlertDialog Builder object.
- Using builder object create AlertDialog object.
- Using SetMessage and SetTitle set the Body message and Title respectively.
- Now set three buttons using their specific methods SetButton, SetButton2 and SetButton3.
The latter two are optional. SetButton* method contain two parameter one is string
text to display and second is its onClick Handller.
- In OnClick handler, we are using Toast to display the button text.
- In the end, use Show() method to display AlertDialog.
- Build and Run DEMO I
Demo 1
|
| Demo 1
|
|
|
|
- Now in Part 2, we will show ListView inside the AlertDialog. For doing that you
need to create BaseAdapter and plug it with ListView. For doing it you need to create
BaseAdapter, the code is as follow:-
internal class AlertListViewAdapter: BaseAdapter<string>
{
Activity _context = null;
List<String> _lstDataItem = null;
public AlertListViewAdapter (Activity context, List<String> lstDataItem)
{
_context = context;
_lstDataItem = lstDataItem;
}
#region implemented abstract members of BaseAdapter
public override long GetItemId (int position)
{
return position;
}
public override View GetView (int position, View convertView, ViewGroup parent)
{
if (convertView == null)
convertView = _context.LayoutInflater.Inflate (Android.Resource.Layout.SimpleListItem1, null);
(convertView.FindViewById<TextView> (Android.Resource.Id.Text1))
.SetText (this [position], TextView.BufferType.Normal);
return convertView;
}
public override int Count {
get {
return _lstDataItem.Count;
}
}
#endregion
#region implemented abstract members of BaseAdapter
public override string this [int index] {
get {
return _lstDataItem [index];
}
}
#endregion
}
You can read more about creating and using BaseAdapter in ListView here
- Now in MainActivity.cs file, add EventHandller for second button, add following
code inside the handler:-
btnNormalDialog = FindViewById<Button> (Resource.Id.myButton1);
btnNormalDialog.Click += methodInvokeAlertDialogWithListView;
Also create local field of generic collection list of type string. This collection
will hold items to be displayed inside the listview.
_lstDataItem.Add ("Person 1");
_lstDataItem.Add ("Person 2");
_lstDataItem.Add ("Person 3");
_lstDataItem.Add ("Person 4");
-
To add listview inside the AlertDialog, you will first create ListView object, attach
the adapter to it and in the end using SetView method attach ListView to AlertDialog.
#region ListView AlertDialog
void methodInvokeAlertDialogWithListView (object sender, EventArgs e)
{
var dlgAlert = (new AlertDialog.Builder (this)).Create ();
dlgAlert.SetTitle ("List View Alert Dialog");
var listView = new ListView (this);
listView.Adapter = new AlertListViewAdapter (this, _lstDataItem);
listView.ItemClick += listViewItemClick;
dlgAlert.SetView (listView);
dlgAlert.SetButton ("OK", handllerNotingButton);
dlgAlert.Show ();
}
void listViewItemClick (object sender, AdapterView.ItemClickEventArgs e)
{
Toast.MakeText (this, "you clicked on " + _lstDataItem [e.Position], ToastLength.Short).Show ();
}
#endregion
Here I am displaying the clicked item in Toast.
- Build and Run DEMO II
Demo 2
|
| Demo 2
|
|
|
|
Second Image is result of clicking “Person 3” list-item.
- In the Demo III, we will include custom layout inside the alert dialog. For that
in layout folder, add new layout file by name AlertDialogLayout.axml. Following
is the xml code for file :-
="1.0"="utf-8"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<RelativeLayout
android:minWidth="25px"
android:minHeight="25px"
android:layout_width="fill_parent"
android:layout_height="110.7dp"
android:id="@+id/relativeLayout1">
<ImageView
android:src="@android:drawable/ic_menu_gallery"
android:id="@+id/imageView1"
android:layout_width="75.3dp"
android:layout_height="wrap_content" />
<TextView
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_width="146.0dp"
android:layout_height="90.7dp"
android:id="@+id/textView1"
android:layout_toRightOf="@+id/imageView1"
android:layout_marginRight="10.7dp" />
<ImageView
android:src="@android:drawable/ic_menu_gallery"
android:id="@+id/imageView2"
android:layout_width="75.3dp"
android:layout_toRightOf="@+id/textView1"
android:layout_height="wrap_content" />
</RelativeLayout>
</LinearLayout>
I used following step to create above layout
- First add Relative Layout
- Now push image view (id:
imageView1
) inside relative layout - Then push textview (id:
textView1
) in right of imageView1
- Push another image view(id:
imageView2
) in right of textView1
- Since I am using two images in above layout, I have included following two images in the project:-
Resource.Drawable.Icon1
|
| Resource.Drawable.Icon2
|
|
|
|
- Now add following code in the relevant button click handler :-
void methodInvokeAlertDialogWithCustomView (object sender, EventArgs e)
{
var dlgAlert = (new AlertDialog.Builder (this)).Create ();
dlgAlert.SetTitle ("Sample Alert Dialog");
var viewAD = this.LayoutInflater.Inflate (Resource.Layout.AlertDialogLayout, null);
viewAD.FindViewById<TextView> (Resource.Id.textView1).SetText ("Message From Layout",TextView.BufferType.Normal);
viewAD.FindViewById<ImageView> (Resource.Id.imageView1).SetImageResource(Resource.Drawable.Icon1);
viewAD.FindViewById<ImageView> (Resource.Id.imageView2).SetImageResource(Resource.Drawable.Icon2);
dlgAlert.SetView (viewAD);
dlgAlert.SetButton ("OK", handllerNotingButton);
dlgAlert.Show ();
}
Following in explanation of above code:-
- Inflate the AlertDialogLayout using LayoutInflater.Inflate method into relevant View object (object:
viewAD
). - Using FindViewById method to set text and images in relevant controls
- Using AlertDialog object SetView method, set
viewAD
view inside the AlertDialog
- Build and run DEMO III
Demo 2
|
|
Points of Interest
I have used MonoAndroid for C# and Xamarin Studio to build this tutorial. Watch out,
if I continue learning it, you can expect more articles coming soon.
Though Xamarin Studio is proprietary software, however they provide free
starter version to built, test and publish android application. I am using same
for my learning and creating step by step tutorials here.
Articles in this series!
Tips/Tricks in this Series
History
- 22-Nov-2013: First Version