Click here to Skip to main content
Click here to Skip to main content

MonoAndroid: Using AlertDialog

, 21 Nov 2013
Rate this:
Please Sign up or sign in to vote.
Article demonstrating use of Alert-Dialog in android universe.

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

  1. Create Android application by selecting New ->Solutions and provide its name “AndroidAlertDialogDemo

      


  2.  
  3. 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:-
     
    <?xml version="1.0" encoding="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



  4. 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;
    

  5. 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. 

  6. Build and Run DEMO I

    Demo 1
      Demo 1
        


  7. 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



  8. 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");
    
  9. 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. 


  10. Build and Run DEMO II

    Demo 2   Demo 2
      

    Second Image is result of clicking “Person 3” list-item.


  11. 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 :-
      
    <?xml version="1.0" encoding="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


  12. Since I am using two images in above layout, I have included following two images in the project:-

    Resource.Drawable.Icon1   Resource.Drawable.Icon2
     


  13. 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

  14. 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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

ThatsAlok
Software Developer (Senior)
India India
He used to have biography here Smile | :) , but now he will hire someone (for free offcourse Big Grin | :-D ), Who writes his biography on his behalf Smile | :)
 
He is Great Fan of Mr. Johan Rosengren (his idol),Lim Bio Liong, Nishant S and DavidCrow and Believes that, he will EXCEL in his life by following there steps!!!
 

For good 8 years he was Visual CPP MSMVP!

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web03 | 2.8.140814.1 | Last Updated 22 Nov 2013
Article Copyright 2013 by ThatsAlok
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid