Dialogs in Android

Introduction

 
It is quite fascinating when you select or choose something and a small window prompts you before your screen asks for your choice. So these small prompts that take the user's wish as input are called a Dialog in Android.
 
Let us consider the example of when we delete a file in our Android supported phone. A window then prompts “Do you want to reboot in safe mode?”. You then have two choices, either press Yes or press No. So this might be a very good and lucid example.
 
Dialog in android with button
 

Dialog Design

 
Generally, the design consists of a basic title and simple action buttons.
  • Optional title region
     
    First, it contains the section of the title that shows or tells the user which type of prompt it is and appropriately the user responds to it.
  • Content area
     
    The Content area is just below the title of the dialog box such that it contains the full information about the problem or the resource that helps the user to act or respond appropriately.
  • Action buttons
     
    Action buttons are the last layer in the dialog design. Generally, it contains mainly two buttons, more precisely action buttons or certainly checks boxes may be there.
Note: The Acceptance action part of the buttons is always on the right side and a dismissive action part must be on the left. The affirmative or positive action result is in the continuation of the process and on the contrary, the negative response leads back to the activity or previous state. The Dialog class is the parent class of all types of dialogs, meanwhile when a subclass that is extending the Dialog class, the programmer must see all the key aspects of the class.
 

Alert dialog

 
An Alert dialog can show a title and up to three buttons for a list of selected items or a custom layout.DatePickerDialog or TimePickerDialog. It is a dialog with the pre-defined user interface that allows the user to select a date or time.
 

Dialog fragment class

 
Instead of using the preceding specified classes, we must use the DialogFragment as a container. The preceding classes define classes that show or maintain the style property. The DialogFragment class provides all the controls you need to create for your dialog and manage its appearance, instead of calling methods on the Dialog object.
 
Using the DialogFragment class does not even change or distort the original code or doesn't spoil the lifecycle. This class provides or allows you to reuse the dialog's user interface as an embeddable component in a larger user interface.
 

Creating the Dialog fragment

 
Dialogs design guides just by extending DialogFragment and creating an AlertDialog in the onCreateDialog() callback method.
 
For example, here's a basic AlertDialog that's managed within a DialogFragment.
 
Manifest file:
  1. <?xml version="1.0" encoding="utf-8"?>      
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"      
  3.     package="com.example.alertdialog"      
  4.     android:versionCode="1"      
  5.     android:versionName="1.0" >      
  6.       
  7.     <uses-sdk      
  8.         android:minSdkVersion="11"      
  9.         android:targetSdkVersion="21" />      
  10.       
  11.     <application      
  12.         android:allowBackup="true"      
  13.         android:icon="@drawable/ic_launcher"      
  14.         android:label="@string/app_name"      
  15.         android:theme="@style/AppTheme" >      
  16.         <activity      
  17.             android:name="com.example.alertdialog.MainActivity"      
  18.             android:label="@string/app_name" >      
  19.             <intent-filter>      
  20.                 <action android:name="android.intent.action.MAIN" />      
  21.       
  22.                 <category android:name="android.intent.category.LAUNCHER" />      
  23.             </intent-filter>      
  24.         </activity>      
  25.     </application>      
  26.       
  27. </manifest>     
    Now we have defined the manifest here that includes a target and minimum SDK support and much more as shown in the code. Now it is time to define the attributes to the XML file.
     
    Defining the attributes to the activity_main.xml file all the resources must be defined here.
     
    Activity_main.xml
    1. <?xml version="1.0" encoding="utf-8"?>      
    2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"      
    3.     android:layout_width="match_parent"      
    4.     android:layout_height="match_parent" >      
    5.           
    6.     <EditText       
    7.         android:id="@+id/EditText01"       
    8.         android:text="I Love Android"      
    9.         android:layout_height="50dip"       
    10.         android:layout_width="180dip">      
    11.               
    12.     </EditText>      
    13.           
    14.     <Button       
    15.        android:id="@+id/Button01"       
    16.        android:layout_width="wrap_content"      
    17.        android:layout_height="wrap_content"       
    18.        android:layout_below="@+id/EditText"      
    19.        android:text="Clear Screen">      
    20.               
    21.     </Button>       
    22.       
    23. </RelativeLayout>     
    MainActivity.java
    1. package com.gkumar.example.alertdialog;      
    2.       
    3. import android.support.v7.app.ActionBarActivity;      
    4. import android.support.v7.app.ActionBar;      
    5. import android.support.v4.app.Fragment;      
    6. import android.app.AlertDialog;      
    7. import android.app.Dialog;      
    8. import android.content.DialogInterface;      
    9. import android.os.Bundle;      
    10. import android.view.LayoutInflater;      
    11. import android.view.Menu;      
    12. import android.view.MenuItem;      
    13. import android.view.View;      
    14. import android.view.ViewGroup;      
    15. import android.widget.Button;      
    16. import android.widget.EditText;      
    17. import android.widget.Toast;      
    18. import android.os.Build;      
    19.       
    20. public class MainActivity extends ActionBarActivity     
    21. {      
    22.        Button Clear;      
    23.        EditText edit_data;      
    24.        //Called when the activity is first created      
    25.        @Override      
    26.        public void onCreate(Bundle savedInstanceState)     
    27.        {      
    28.              super.onCreate(savedInstanceState);      
    29.              setContentView(R.layout.main);      
    30.            
    31.              Clear=(Button)findViewById(R.id.Button01);      
    32.              edit_data=(EditText)findViewById(R.id.EditText01);      
    33.            
    34.              Clear.setOnClickListener(new View.OnClickListener()     
    35.              {      
    36.               
    37.                    @Override      
    38.                    public void onClick(View v)     
    39.                    {      
    40.                   
    41.                         AlertDialog.Builder builder=new AlertDialog.Builder(v.getContext());      
    42.                         //Set a title      
    43.                         builder.setTitle("Confirm");      
    44.                         //Set a message      
    45.                         builder.setMessage("Do you want to Clear?");      
    46.                         ////Here Set a listener to be called when the positive button of the dialog is pressed.      
    47.                         builder.setPositiveButton("OK",new DialogInterface.OnClickListener()    
    48.                         {      
    49.                    
    50.                               @Override      
    51.                                public void onClick(DialogInterface dialog, int which)    
    52.                               {      
    53.                              
    54.                                         
    55.                                     edit_data.setText("");      
    56.                                     //Displaying a toast message      
    57.                                     Toast.makeText(getApplicationContext(), "Your text has been cleared", Toast.LENGTH_LONG).show();      
    58.                               }      
    59.     
    60.                          });      
    61.                          
    62.                          builder.setNegativeButton("Cancel",new DialogInterface.OnClickListener()     
    63.                          {      
    64.            
    65.                               @Override      
    66.                               public void onClick(DialogInterface dialog, int which)     
    67.                               {      
    68.                                      // TODO Auto-generated method stub      
    69.                                      dialog.cancel();      
    70.                               }      
    71.                          });      
    72.                  
    73.                          //Creating the dialog      
    74.                          AlertDialog alertdialog=builder.create();      
    75.            
    76.                          //show the alertdialog      
    77.                          alertdialog.show();      
    78.            
    79.                    }      
    80.              });      
    81.        }      
    82.           
    83. }     
    Here depending upon the complexity of the dialog created we can implement a variety of callbacks methods.
     

    Adding a list

     
    There are the following three kinds of lists available with the AlertDialog APIs.
    •  A traditional single choice list
       
    •  A persistent single choice list (radio buttons)
       
    •  A persistent multiple-choice list (check boxes)
    Here let us create a list having three choices with the sentItems() method.
    1. @Override    
    2. public Dialog onCreateDialog(Bundle savedInstanceState) {    
    3.     AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());    
    4.     builder.setTitle(R.string.pick_color)    
    5.            .setItems(R.array.colors_array, new DialogInterface.OnClickListener() {    
    6.                public void onClick(DialogInterface dialog, int which) {    
    7.                // The 'which' argument contains the index position    
    8.                // of the selected item    
    9.            }    
    10.     });    
    11.     return builder.create();   
      In this code above we have three choices in the list.
       

      Summary

       
      This article explained the basics of dialogs that appear on Android devices that ask the choice of the user or alert dialog that also asks for the user's choice. Depending upon the work the user is doing, the dialog appears and asks to continue to the next work and also to modify the current work. 


      Similar Articles