Android AlertDialog


In order to prompt any alert message to user, we need to use widget – Android AlertDialog. This tutorial will cover adding title, message description, icon, buttons to Android AlertDialog inside file.


Download Source Code :


Now Let us work on Project : (Refer – Configuring Existing AndroidStudioProject) AlertDialog which you might have downloaded from above or you can follow the scripts below by copying it to implement in your Project. To launch Downloaded project, Extract the zip, copy it into AndroidStudioProjects. Now from Android Studio click open Existing Android Studio Project and select the path to extracted file we just copied in AndroidStudioProjects directory. If Sync SDK path prompt comes just click OK and you are ready to work. If still you get error check for AndroidStudioProjects/AlertDialog/app/build.gradle , it will contain different SDK Version. Change it to SDK Version which you have.




Explaining above Code :

  • Line 12 We added an instance of Context ( content provider ) which we will require while making AlertDialog Builder & showing Toast.
  • Line 21 We declare AlertDialog Buider which we are going to use to show AlertDialog.
  • Line 24 At this line we provide Title to our Android AlertDialog.
  • Line 27-30 We add some more properties to our AlertDialog like Message, title-bar Icon, Cancelable. We have added Icon from Drawables folder inside Resources. Cancelable property setting to false,  makes it compulsory for user to select from either of the available option, without that he/she cannot quit the alert box. Observe that we have not added semi-colon at end of these lines.
  • Line 31 We add our 1st button to AlertDialog. And inside it we place a method which will be invoked when user clicks on this button. ( We regarded this button as Positive button since we are going to perform some affirmative action, yet it is not compulsory )
  • Line 39 In the same way we declared our Negative button, with click-listener inside it.
  • Line 48-49 Until now we have just assigned properties to our AlertDialog, at this point we make it shown to user.


2. activity_main.xml : Layout file

  • So as to add Android AlertDialog you do not need to add anything separately from activity_main.xml.



Final Output :

Android AlertDialog


Do It Yourself :

  • Apart from positive-negative button add 3rd neutral button in same way we added previous 2 buttons. Also try some title & message font colors.


Report Errors + Bugs & Become Insider for

We would like to hear you, if you find any error or misspelled phrase while reading our tutorials. By reporting mistakes through email to you could help other peers.