Androd Dialogs

Introduction

 
When developing an app, one of the basic ways to show a user something important is through a dialog. 
 
A dialog is a small popup message with one or two buttons to show the user an important message or to ask the user for some input.
 
There are various ways to generate a simple dialog. I will be showing four general-purpose dialogs that I have used the most.
 
Simple Dialog, Date picker, Time Picker and using my own layout in a dialog.
 
Let's create a sample project.
 
From the previous articles, we have borrowed the "button_background.xml" file in the drawable folder.
 
drawable/button_background.xml
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <selector xmlns:android="http://schemas.android.com/apk/res/android" >  
  3.    
  4.   <!-- disabled -->  
  5.   <item android:state_enabled="false" >  
  6.        <shape android:shape="rectangle">  
  7.             <gradient  
  8.                    android:startColor="#454545"  
  9.                 android:endColor="#454545"  
  10.                    android:angle="-90"  
  11.                    android:type="linear"  
  12.                    />  
  13.                <corners android:radius="5dp" />  
  14.         </shape>  
  15.     </item>  
  16.    
  17.  <!-- pressed -->  
  18.   <item android:state_pressed="true" android:state_enabled="true" >  
  19.        <shape android:shape="rectangle">  
  20.             <gradient  
  21.                    android:startColor="#64334C"  
  22.                 android:endColor="#300019"  
  23.                    android:angle="-90"  
  24.                    android:type="linear"  
  25.                    />  
  26.                <corners android:radius="5dp" />  
  27.         </shape>  
  28.     </item>  
  29.    
  30.   <!-- focused -->  
  31.   <item android:state_focused="true">  
  32.       <shape android:shape="rectangle">  
  33.             <gradient  
  34.                    android:startColor="#C76699"  
  35.                 android:endColor="#610033"  
  36.                    android:angle="-90"  
  37.                    android:type="linear"  
  38.                    />  
  39.                <corners android:radius="5dp" />  
  40.                <stroke android:width="2dp" android:color="#dddddd"/>  
  41.         </shape>  
  42.     </item>  
  43.    
  44.       <!-- default -->  
  45.     <item>  
  46.         <shape android:shape="rectangle">  
  47.             <gradient  
  48.                    android:startColor="#C76699"  
  49.                 android:endColor="#610033"  
  50.                    android:angle="-90"  
  51.                    android:type="linear"  
  52.                    />  
  53.                <corners android:radius="5dp" />  
  54.         </shape>  
  55.     </item>  
  56. </selector> 
Now open the activity_main.xml file and add four buttons to it. These buttons will be used to show dialogs.
 
activity_main.xml
  1. <LinearLayout 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.     tools:context=".MainActivity"  
  6.     android:orientation="vertical"  
  7.     >  
  8.     <Button  
  9.         android:id="@+id/simpleDialogButton"  
  10.         android:layout_height="wrap_content"  
  11.         android:layout_width="match_parent"  
  12.         android:layout_margin="10dp"  
  13.         android:text="Simple Dialog"  
  14.         android:background="@drawable/button_background"  
  15.         android:textColor="#ffffff"  
  16.         />  
  17.     <Button  
  18.         android:id="@+id/timeDialogButton"  
  19.         android:layout_height="wrap_content"  
  20.         android:layout_width="match_parent"  
  21.         android:layout_margin="10dp"  
  22.         android:text="Time Dialog"  
  23.         android:background="@drawable/button_background"  
  24.         android:textColor="#ffffff"  
  25.         />  
  26.     <Button  
  27.         android:id="@+id/dateDialogButton"  
  28.         android:layout_height="wrap_content"  
  29.         android:layout_width="match_parent"  
  30.         android:layout_margin="10dp"  
  31.         android:text="Date Dialog"  
  32.         android:background="@drawable/button_background"  
  33.         android:textColor="#ffffff"  
  34.         />  
  35.     <Button  
  36.         android:id="@+id/customDialogButton"  
  37.         android:layout_height="wrap_content"  
  38.         android:layout_width="match_parent"  
  39.         android:layout_margin="10dp"  
  40.         android:text="Custom Dialog"  
  41.         android:background="@drawable/button_background"  
  42.         android:textColor="#ffffff"  
  43.         />  
  44. </LinearLayout> 
For one of our custom layouts create a file custom_dialog_layout.xml in the layout folder.
 
layout/custom_dialog_layout.xml
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:orientation="vertical"  
  6.     android:gravity="center_horizontal">  
  7.   
  8.     <RadioGroup  
  9.         android:id="@+id/radioGroup1"  
  10.         android:layout_width="wrap_content"  
  11.         android:layout_height="wrap_content"  
  12.         >  
  13.   
  14.         <RadioButton  
  15.             android:id="@+id/radio0"  
  16.             android:layout_width="wrap_content"  
  17.             android:layout_height="wrap_content"  
  18.             android:checked="true"  
  19.             android:text="Option1" />  
  20.   
  21.         <RadioButton  
  22.             android:id="@+id/radio1"  
  23.             android:layout_width="wrap_content"  
  24.             android:layout_height="wrap_content"  
  25.             android:text="Option2" />  
  26.   
  27.         <RadioButton  
  28.             android:id="@+id/radio2"  
  29.             android:layout_width="wrap_content"  
  30.             android:layout_height="wrap_content"  
  31.             android:text="Option3" />  
  32.     </RadioGroup>  
  33.     <Button  
  34.             android:id="@+id/okButton"  
  35.             android:layout_height="wrap_content"  
  36.             android:layout_width="100dp"  
  37.             android:padding="10dp"  
  38.             android:text="Ok"  
  39.             />  
  40. </LinearLayout> 
Now MainActivity.java has all the code you need to make the dialogs, for proper clarification of the syntax please check the comments in the code.
  1. public class MainActivity extends Activity {  
  2.   
  3.     @Override  
  4.     protected void onCreate(Bundle savedInstanceState) {  
  5.         super.onCreate(savedInstanceState);  
  6.         setContentView(R.layout.activity_main);  
  7.          
  8.         /* 
  9.          * Add listeners to the buttons and call the appropriate methods 
  10.          */  
  11.          
  12.         ((Button)findViewById(R.id.simpleDialogButton)).setOnClickListener(new OnClickListener() {  
  13.              
  14.             @Override  
  15.             public void onClick(View v) {  
  16.                 // TODO Auto-generated method stub  
  17.                 createSimpleDialog();  
  18.             }  
  19.         });  
  20.         ((Button)findViewById(R.id.dateDialogButton)).setOnClickListener(new OnClickListener() {  
  21.              
  22.             @Override  
  23.             public void onClick(View v) {  
  24.                 // TODO Auto-generated method stub  
  25.                 createDateDialog();  
  26.             }  
  27.         });  
  28.         ((Button)findViewById(R.id.timeDialogButton)).setOnClickListener(new OnClickListener() {  
  29.              
  30.             @Override  
  31.             public void onClick(View v) {  
  32.                 // TODO Auto-generated method stub  
  33.                 createTimeDialog();  
  34.             }  
  35.         });  
  36.         ((Button)findViewById(R.id.customDialogButton)).setOnClickListener(new OnClickListener() {  
  37.              
  38.             @Override  
  39.             public void onClick(View v) {  
  40.                 // TODO Auto-generated method stub  
  41.                 createCustomDialog();  
  42.             }  
  43.         });  
  44.     }  
  45.   
  46.     /* 
  47.      * This is a convenient method to show a toast after dismissing the dialog 
  48.      */  
  49.     private void showToast(String toastString)  
  50.     {  
  51.         Toast.makeText(MainActivity.this, toastString, Toast.LENGTH_SHORT).show();  
  52.     }  
  53.      
  54.     /* 
  55.      * This is the basic method to create a dialog 
  56.      * This sets a message and two buttons to the dialog 
  57.      */  
  58.     private void createSimpleDialog()  
  59.     {  
  60.         AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);  
  61.         builder.setMessage("This is simple dialog")  
  62.                .setPositiveButton("Ok"new DialogInterface.OnClickListener() {  
  63.                    public void onClick(DialogInterface dialog, int id) {  
  64.                        showToast("Simple dialog Ok button pressed");  
  65.                    }  
  66.                })  
  67.                .setNegativeButton("Cancel"new DialogInterface.OnClickListener() {  
  68.                    public void onClick(DialogInterface dialog, int id) {  
  69.                        showToast("Simple dialog Cancel button pressed");  
  70.                    }  
  71.                });  
  72.         builder.create().show();  
  73.     }  
  74.      
  75.     /* 
  76.      * This method used the builtin DatePickerDialog to ask user to select a date 
  77.      * We use a Calendar instance to get the current date, we also add a listener(OnDateSetListener) to the dialog to get the selected date  
  78.      */  
  79.     private void createDateDialog(){  
  80.         Calendar c = Calendar.getInstance();  
  81.         DatePickerDialog dialog = new DatePickerDialog(MainActivity.this, mDateSetListener, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));  
  82.         dialog.show();  
  83.     }  
  84.      
  85.     /* 
  86.      * This listener is called when we select date in the DatePickerDialog 
  87.      */  
  88.     OnDateSetListener mDateSetListener = new OnDateSetListener() {  
  89.          
  90.         @Override  
  91.         public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {  
  92.             // TODO Auto-generated method stub  
  93.              
  94.             showToast("Selected date: "+dayOfMonth+"/"+(monthOfYear+1)+"/"+year);  
  95.         }  
  96.     };  
  97.      
  98.   
  99.     /* 
  100.      * This method used the builtin TimePickerDialog to ask user to select a date 
  101.      * We use a Calendar instance to get the current time, we also add a listener(OnTimeSetListener) to the dialog to get the selected time  
  102.      */  
  103.     private void createTimeDialog() {  
  104.         Calendar c = Calendar.getInstance();  
  105.         TimePickerDialog dialog = new TimePickerDialog(MainActivity.this, mTimeSetListener, c.get(Calendar.HOUR), c.get(Calendar.MINUTE), false);  
  106.         dialog.show();  
  107.     }  
  108.      
  109.     /* 
  110.      * This listener is called when we select time in the TimePickerDialog 
  111.      */  
  112.     OnTimeSetListener mTimeSetListener = new OnTimeSetListener() {  
  113.          
  114.         @Override  
  115.         public void onTimeSet(TimePicker view, int hourOfDay, int minute) {  
  116.             // TODO Auto-generated method stub  
  117.             showToast("Selected time: "+hourOfDay+":"+minute);  
  118.         }  
  119.     };  
  120.      
  121.     /* 
  122.      * This method creates a custom dialog using the layout we has created previously 
  123.      */  
  124.     private void createCustomDialog(){  
  125.         //Create a dialog object  
  126.         final Dialog dialog = new Dialog(MainActivity.this);  
  127.         //Set its layout  
  128.         dialog.setContentView(R.layout.custom_dialog_layout);  
  129.         //Set the title  
  130.         dialog.setTitle("This is custom layout");  
  131.         //Make it cancelable  
  132.         dialog.setCancelable(true);  
  133.         //We need to dismiss the dialog so we add a listener to the ok button  
  134.         dialog.findViewById(R.id.okButton).setOnClickListener(new OnClickListener() {  
  135.              
  136.             @Override  
  137.             public void onClick(View v) {  
  138.                 // TODO Auto-generated method stub  
  139.                 dialog.dismiss();  
  140.             }  
  141.         });  
  142.          
  143.         dialog.show();  
  144.     }  
This is the very basic code to make an interesting UI. We can always use the custom dialogs to create a very user interactive app but don't overdo it or it may end up being too much of a hassle for the user.
 
Screenshots:
 
Article5Img1.png
   
Article5Img2.png
 
Article5Img3.png
 
Article5Img4.png


Similar Articles