Alert DialogBox in Android

Introduction

 
Dialog Boxes are mainly used for showing some information to the user. This information may be related to a specific task or to an error or it may be some kind of general information.
 
Now we move to the code part of this article.
 
First of all, we create an XML file for our project. We are using two Activities in this project. Our first activity is activity_main.xml.
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    
  2.     xmlns:tools="http://schemas.android.com/tools"    
  3.     android:layout_width="match_parent"    
  4.     android:layout_height="match_parent"    
  5.     android:paddingBottom="@dimen/activity_vertical_margin"    
  6.     android:paddingLeft="@dimen/activity_horizontal_margin"    
  7.     android:paddingRight="@dimen/activity_horizontal_margin"    
  8.     android:paddingTop="@dimen/activity_vertical_margin"    
  9.     tools:context=".MainActivity" >    
  10.     
  11.     <TextView    
  12.         android:id="@+id/textView1"    
  13.         android:layout_width="wrap_content"    
  14.         android:layout_height="wrap_content"    
  15.         android:text="@string/hello_world" />    
  16.     
  17.     <Button    
  18.         android:id="@+id/button1"    
  19.         android:layout_width="wrap_content"    
  20.         android:layout_height="wrap_content"    
  21.         android:layout_below="@+id/textView1"    
  22.         android:layout_centerHorizontal="true"    
  23.         android:layout_marginTop="64dp"    
  24.         android:text="@string/button1" />    
  25.     
  26.     <Button    
  27.         android:id="@+id/button2"    
  28.         android:layout_width="wrap_content"    
  29.         android:layout_height="wrap_content"    
  30.         android:layout_alignLeft="@+id/button1"    
  31.         android:layout_below="@+id/button1"    
  32.         android:layout_marginTop="28dp"    
  33.         android:text="@string/button2" />    
  34.     
  35.     <Button    
  36.         android:id="@+id/button3"    
  37.         android:layout_width="wrap_content"    
  38.         android:layout_height="wrap_content"    
  39.         android:layout_alignLeft="@+id/button2"    
  40.         android:layout_below="@+id/button2"    
  41.         android:layout_marginTop="30dp"    
  42.         android:text="@string/button3" />    
  43.     
  44. </RelativeLayout>   
Graphical Layout of Activity
 
Graphical Layout of Activity
 
In the preceding code, we use a Relative Layout. In this Layout, we use a TextView. In this TextView, we will show some text in the activity. We also use 3 buttons in this activity. Using these 3 buttons we will show 3 types of Alert Dialog Boxes. On click of the “Alert Type 1“ button, we will show a simple Dialog Box with a single option. On the click of the “Alert Type 2” button, we will show a dialog box that has two options. Finally on the click of “Alert Type 3,” we will show a dialog box that contains a ListView. This ListView is present in the menu_detail_fragment activity. Now we move to our second activity.
 
menu_detail_fragment.xml
  1. <?xml version="1.0" encoding="utf-8"?>    
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    
  3.     android:orientation="vertical"    
  4.     android:layout_width="match_parent"    
  5.     android:gravity="center"    
  6.     android:background="#5ba4e5"    
  7.     android:layout_height="match_parent">    
  8.      <ListView    
  9.         android:id="@+id/listView1"    
  10.         android:layout_width="match_parent"    
  11.         android:layout_height="wrap_content"    
  12.       android:layout_marginTop="25dp" >    
  13.     </ListView>    
  14.     
  15. </LinearLayout>   
    Graphical Layout
     
    Graphical Layout
     
    In this ListView, we will insert some data and show this ListView using a dialog box.
     
    Now we move to the source code of this project.
     
    The following  is the source code,
    1. public class MainActivity extends Activity {    
    2.     
    3.     Button B1, B2, B3;    
    4.     ArrayAdapter < String > adapter;@Override    
    5.     protected void onCreate(Bundle savedInstanceState) {    
    6.         super.onCreate(savedInstanceState);    
    7.         setContentView(R.layout.activity_main);    
    8.     
    9.         B1 = (Button) findViewById(R.id.button1);    
    10.         B2 = (Button) findViewById(R.id.button2);    
    11.         B3 = (Button) findViewById(R.id.button3);    
    12.     
    13.         B1.setOnClickListener(new View.OnClickListener() {    
    14.     
    15.             @Override    
    16.             public void onClick(View arg0) {    
    17.                 // TODO Auto-generated method stub    
    18.     
    19.                 final AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();    
    20.                 alertDialog.setTitle("Alert Dialog");    
    21.                 alertDialog.setMessage("Welcome to My Device");    
    22.                 alertDialog.setIcon(R.drawable.icon_smile);    
    23.     
    24.                 alertDialog.setButton("OK"new DialogInterface.OnClickListener() {    
    25.                     public void onClick(DialogInterface dialog, int which) {    
    26.     
    27.                         Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();    
    28.     
    29.                     }    
    30.                 });    
    31.     
    32.                 alertDialog.show();    
    33.     
    34.             }    
    35.         });    
    36.     
    37.         B2.setOnClickListener(new View.OnClickListener() {    
    38.     
    39.             @Override    
    40.             public void onClick(View arg0) {    
    41.                 // TODO Auto-generated method stub    
    42.                 //alertDialog.setButton2(text, listener)    
    43.                 AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);    
    44.                 alertDialog.setTitle("Alert Dialog");    
    45.                 alertDialog.setMessage("Welcome to DZone");    
    46.                 alertDialog.setIcon(R.drawable.icon_smile);    
    47.     
    48.                 alertDialog.setPositiveButton("YES"new DialogInterface.OnClickListener() {    
    49.                     public void onClick(DialogInterface dialog, int which) {    
    50.                         Toast.makeText(getApplicationContext(), "You clicked on YES", Toast.LENGTH_SHORT).show();    
    51.                     }    
    52.                 });    
    53.     
    54.                 alertDialog.setNegativeButton("NO"new DialogInterface.OnClickListener() {    
    55.                     public void onClick(DialogInterface dialog, int which) {    
    56.                         Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT).show();    
    57.                     }    
    58.                 });    
    59.     
    60.                 alertDialog.show();    
    61.             }    
    62.         });    
    63.     
    64.         B3.setOnClickListener(new View.OnClickListener() {    
    65.     
    66.             @Override    
    67.             public void onClick(View arg0) {    
    68.                 // TODO Auto-generated method stub    
    69.                 AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);    
    70.                 alertDialog.setTitle("Alert Dialog");    
    71.                 alertDialog.setMessage("Welcome to My Device");    
    72.                 alertDialog.setIcon(R.drawable.icon_smile);    
    73.     
    74.     
    75.                 final String names[] = {    
    76.                     "Item1""Item2""Item3""Item4"    
    77.                 };    
    78.                 // AlertDialog.Builder alertDialog2 = new AlertDialog.Builder(MainActivity.this);    
    79.                 LayoutInflater inflater = getLayoutInflater();    
    80.                 View convertView = (View) inflater.inflate(R.layout.menu_detail_fragment, null);    
    81.                 alertDialog.setView(convertView);    
    82.                 alertDialog.setTitle("List");    
    83.                 ListView lv = (ListView) convertView.findViewById(R.id.listView1);    
    84.                 adapter = new ArrayAdapter < String > (MainActivity.this, android.R.layout.simple_list_item_1, names);    
    85.                 lv.setAdapter(adapter);    
    86.                 alertDialog.show();    
    87.     
    88.                 lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {    
    89.     
    90.                     @Override    
    91.                     public void onItemClick(AdapterView <? > parent, View view,    
    92.                     int position, long id) {    
    93.                         Toast.makeText(MainActivity.this"You Clicked at " + names[+position], Toast.LENGTH_SHORT).show();    
    94.     
    95.                     }    
    96.                 });    
    97.             }    
    98.         });    
    99.     
    100.     }    
    101. }   
      Now I will explain the preceding code in the following code sections for a better understanding.
       
      Code Section 1
      1. B1.setOnClickListener(new View.OnClickListener() {    
      2.     
      3.     @Override    
      4.     public void onClick(View arg0) {    
      5.         // TODO Auto-generated method stub    
      6.     
      7.         final AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();    
      8.         alertDialog.setTitle("Alert Dialog");    
      9.         alertDialog.setMessage("Welcome to My Device");    
      10.         alertDialog.setIcon(R.drawable.icon_smile);    
      11.     
      12.         alertDialog.setButton("OK"new DialogInterface.OnClickListener() {    
      13.             public void onClick(DialogInterface dialog, int which) {    
      14.     
      15.                 Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();    
      16.     
      17.             }    
      18.         });    
      19.     
      20.         alertDialog.show();    
      21.     
      22.     }    
      23. });   
        In the preceding code, we set an OnClick event for the “Alert Type 1” button. This event will occur when a user clicks on the “Alert Type 1” button. In the preceding code, we create an object of the AlertDialog class using the Builder method. Then we set the title, message, and Icon for the Alert Dialog Box. Using the setButton method we set the type of button that will be shown in the dialog box. We also set an OnClick event for this button. When a person clicks on the “OK” button we will show some text using the Toast.makeText method.
         
        We can see that setButton is not showing in a proper way (crossed by a line). The reason is that the setButton method only works in older versions of an Android device. In the new version of Android devices, we use another method instead of setButton.
         
        When a person clicks on the “Alert Type 1” button, the following action will be performed.
         
        clock ok
         
        Alert Type 1
         
        Code Section 2
        1. B2.setOnClickListener(new View.OnClickListener() {    
        2.     
        3.     @Override    
        4.     public void onClick(View arg0) {    
        5.         // TODO Auto-generated method stub    
        6.         //alertDialog.setButton2(text, listener)    
        7.         AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);    
        8.         alertDialog.setTitle("Alert Dialog");    
        9.         alertDialog.setMessage("Welcome to DZone");    
        10.         alertDialog.setIcon(R.drawable.icon_smile);    
        11.     
        12.         alertDialog.setPositiveButton("YES"new DialogInterface.OnClickListener() {    
        13.             public void onClick(DialogInterface dialog, int which) {    
        14.                 Toast.makeText(getApplicationContext(), "You clicked on YES", Toast.LENGTH_SHORT).show();    
        15.             }    
        16.         });    
        17.     
        18.         alertDialog.setNegativeButton("NO"new DialogInterface.OnClickListener() {    
        19.             public void onClick(DialogInterface dialog, int which) {    
        20.                 Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT).show();    
        21.             }    
        22.         });    
        23.     
        24.         alertDialog.show();    
        25.     }    
        26. });   
          This code will work the same as I explained in the previous code. Instead of a single button we use two buttons (Yes and No) and create an OnClick event for each button. Instead of the setButton method, we use the setPositiveButton method for showing the “Yes” option and the setNegativeButton method for showing the “No” option in the dialog box.
           
          alter dialog
           
          setNegativeButton
           
          Code Section 3
          1. B3.setOnClickListener(new View.OnClickListener() {    
          2.     
          3.     @Override    
          4.     public void onClick(View arg0) {    
          5.         // TODO Auto-generated method stub    
          6.         AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);    
          7.         alertDialog.setTitle("Alert Dialog");    
          8.         alertDialog.setMessage("Welcome to My Device");    
          9.         alertDialog.setIcon(R.drawable.icon_smile);    
          10.     
          11.     
          12.         final String names[] = {    
          13.             "Item1""Item2""Item3""Item4"    
          14.         };    
          15.         // AlertDialog.Builder alertDialog2 = new AlertDialog.Builder(MainActivity.this);    
          16.         LayoutInflater inflater = getLayoutInflater();    
          17.         View convertView = (View) inflater.inflate(R.layout.menu_detail_fragment, null);    
          18.         alertDialog.setView(convertView);    
          19.         alertDialog.setTitle("List");    
          20.         ListView lv = (ListView) convertView.findViewById(R.id.listView1);    
          21.         adapter = new ArrayAdapter < String > (MainActivity.this, android.R.layout.simple_list_item_1, names);    
          22.         lv.setAdapter(adapter);    
          23.         alertDialog.show();    
          24.     
          25.         lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {    
          26.     
          27.             @Override    
          28.             public void onItemClick(AdapterView <? > parent, View view,    
          29.             int position, long id) {    
          30.                 Toast.makeText(MainActivity.this"You Clicked at " + names[+position], Toast.LENGTH_SHORT).show();    
          31.     
          32.             }    
          33.         });    
          34.     }    
          35. });   
            In the preceding code, we will show a ListView using a Dialog Box when someone clicks on the “Alter Type 3” button. In the preceding code, we create an array of string types and insert some data into this array. Using the inflate method of the getLayoutInflater class we get a reference for a menu_detail_fragment layout and insert it into a View type object. Then we get the reference of ListView into the lv object of ListView and bind the string array to a ListView using ArrayAdapter. Finally we create an OnClick event for ListView. Using this method we show the name of the list item, on which a user will click. Assume we click on item number three of the ListView then the output will be the following,
             
            list item
             
            list


            Similar Articles