logo

A dialog is usually a small window that appears in front of the current Activity. The underlying Activity loses focus and the dialog accepts all user interaction. Dialogs are normally used for notifications that should interrupt the user and to perform short tasks that directly relate to the application in progress (such as a progress bar or a login prompt).

The Dialog class is the base class for creating dialogs. In this tutorial we will learn:
1)AlertDialog
2)AlertDialog with List of Items
3)CustomDialog
4)Date Picker
5)Time Picker

So check out the tutorial below to create Dialogs.

Our main screen will look like this:

Let’s create the project.

1. Create Project

Select File -> New -> Other -> Android -> Android Project and create the Android project “com.mobisys.android.ex_alert_dialog”. Enter the following.

2. Create Alert Dialog

An AlertDialog is an extension of the Dialog class. It is capable of constructing most dialog user interfaces and is the suggested dialog type. You should use it for dialogs that use any of the following features:

  • A title
  • A text message
  • One, two, or three buttons
  • A list of selectable items (with optional checkboxes or radio buttons)

To create an AlertDialog, use the AlertDialog.Builder subclass. Get a Builder with AlertDialog.Builder(Context) and then use the class’s public methods to define all of the AlertDialog properties. After you’re done with the Builder, retrieve the AlertDialog object with create().

So in main.xmlcreate a Button i.e following code:

<Button android:id="@+id/Button01" android:layout_width="wrap_content"
		android:layout_height="wrap_content" android:text="Alert Dialog">
	</Button>

and in AlertDExample class write the following code:

((Button)findViewById(R.id.Button01)).setOnClickListener(new View.OnClickListener(){

			@Override
			public void onClick(View v) {
			 
				Builder builder = new AlertDialog.Builder(AlertDExample.this);
		        builder.setMessage("Are You Sure? Want to Quit? ");
		        builder.setCancelable(true);
		        builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog, int which) {
		                dialog.dismiss();
		            	finish();
		            }
		        });
		        builder.setNegativeButton("Wait", new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog, int which) {
		                Toast.makeText(getApplicationContext(),"Ok!!!Activity will continue",Toast.LENGTH_LONG).show();
		            }
		        });
		        AlertDialog dialog = builder.create();
		        dialog.show();
		  
			}
        	
        });

after running the project Output screen will look like:

3. Adding a list to Alert Dialog

To create an AlertDialog with a list of selectable items like the one shown to the right, use the setItems() method:
So in main.xml create another button. i.e.

<Button android:id="@+id/Button02" android:layout_width="wrap_content"
		android:layout_height="wrap_content" 
                android:text="Alert Dialog with List"
		android:layout_marginTop="8dp">

and in AlertDExample class write the following code:

((Button)findViewById(R.id.Button02)).setOnClickListener(new View.OnClickListener(){

			@Override
			public void onClick(View v) {
			 
				final CharSequence[] items = {"Red", "Green", "Blue"};

				AlertDialog.Builder builder = new AlertDialog.Builder(AlertDExample.this);
				builder.setTitle("Pick a color");
				builder.setItems(items, new DialogInterface.OnClickListener() {
				    public void onClick(DialogInterface dialog, int item) {
				        Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
				    }
				});
				AlertDialog alert = builder.create();
				alert.show();	  
			}
        	
        });



after running the project Output screen will look like:

4. Create Custom Dialog

If you want a customized design for a dialog, you can create your own layout for the dialog window with layout and widget elements. After you’ve defined your layout, pass the root View object or layout resource ID to setContentView(View).

For example, to create the dialog shown to the right:

a) Create an XML layout saved as custom_dialog.xml(in (res/layout))

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/layout_root"
              android:orientation="horizontal"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:padding="10dp"
              >
    <ImageView android:id="@+id/image"
               android:layout_width="wrap_content"
               android:layout_height="fill_parent"
               android:layout_marginRight="10dp"
               />
    <TextView android:id="@+id/text"
              android:layout_width="wrap_content"
              android:layout_height="fill_parent"
              android:textColor="#FFF"
              />
</LinearLayout>

b)Set the above layout as the dialog’s content view and write the following in AlertDExample class write the following code:

((Button)findViewById(R.id.Button03)).setOnClickListener(new View.OnClickListener(){

			@Override
			public void onClick(View v) {
				
				Dialog dialog = new Dialog(AlertDExample.this);
				dialog.setContentView(R.layout.custom);
				dialog.setTitle("Custom Dialog")
				TextView text = (TextView) dialog.findViewById(R.id.text);
				text.setText("Hello, this is a custom dialog!");
				ImageView image = (ImageView) dialog.findViewById(R.id.image);
				image.setImageResource(R.drawable.icon);
				dialog.show();	  
			}
        });

after running the project Output screen will look like:


5. DatePicker Dialog

DatePickerDialog is a dialog that allows the user to select a date.
Steps to create DatePicker:
a)The following code creates LinearLayout with a TextView that will display the date and a Button that will open the DatePickerDialog.(in main.xml)

<TextView android:id="@+id/dateDisplay"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""/>
    <Button android:id="@+id/Button04"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change the date"/>



b) add the following members to the class:

private TextView mDateDisplay;
    private int mYear;
    private int mMonth;
    private int mDay;



c)Now add the following code for the onCreate() method:

// capture our View elements
        mDateDisplay = (TextView) findViewById(R.id.dateDisplay);
        ((Button)findViewById(R.id.Button04)).setOnClickListener(new View.OnClickListener(){

			@Override
			public void onClick(View v) {
				//showDialog(DATE_DIALOG_ID);
				
				DatePickerDialog dialog=new DatePickerDialog(AlertDExample.this,mDateSetListener,mYear, mMonth, mDay);
				dialog.show();
				}});
        // get the current date
        final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);

        // display the current date (this method is below)
        updateDisplay();



First, the content is set to the main.xml layout.Then the TextView and Button elements are captured from the layout with findViewById(int) & when the Button is clicked DatePickerDialog is displayed. A new Calendar is created and the current year, month and day are acquired. Finally, the private updateDisplay() method is called in order to fill the TextView with the current date.

d) Add the updateDisplay() method

// updates the date in the TextView
    private void updateDisplay() {
        mDateDisplay.setText(
            new StringBuilder()
                    // Month is 0 based so add 1
                    .append(mMonth + 1).append("-")
                    .append(mDay).append("-")
                    .append(mYear).append(" "));
    }


e)Initialize a new DatePickerDialog.OnDateSetListener as a member of the HelloDatePicker class:

// the callback received when the user "sets" the date in the dialog
    private DatePickerDialog.OnDateSetListener mDateSetListener =
            new DatePickerDialog.OnDateSetListener() {

                public void onDateSet(DatePicker view, int year, 
                                      int monthOfYear, int dayOfMonth) {
                    mYear = year;
                    mMonth = monthOfYear;
                    mDay = dayOfMonth;
                    updateDisplay();
                }
            };

The DatePickerDialog.OnDateSetListener listens for when the user has set the date (by clicking the “Set” button). At that time, the onDateSet() callback method is called, which is defined to update the mYear, mMonth, and mDay member fields with the new date then call the private updateDisplay() method to update the TextView.

f)Run the application.

6. Time Picker Dialog

In this section, you’ll create a TimePickerDialog, which presents the time picker in a floating dialog box at the press of a button. When the time is set by the user, a TextView will update with the new date.
Steps to create TimePicker:
a)Write the follwing code in res/layout/main.xml

<TextView android:id="@+id/timeDisplay"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""/>
    <Button android:id="@+id/Button05"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change the time"/>

This is a basic LinearLayout with a TextView that will display the time and a Button that will open the TimePickerDialog.

b)add the following members to the class:

private TextView mTimeDisplay;
    private int mHour;
    private int mMinute;

This declares variables for the layout elements and time fields.
c)Now add the following code for the onCreate() method:

// capture our View elements
        mTimeDisplay = (TextView) findViewById(R.id.timeDisplay);
       ((Button)findViewById(R.id.Button05)).setOnClickListener(new View.OnClickListener(){

			@Override
			public void onClick(View v) {
				//showDialog(DATE_DIALOG_ID);
				
				TimePickerDialog dialog=new TimePickerDialog(AlertDExample.this,mTimeSetListener,mHour, mMinute, false);
		        dialog.show();
				}});

        // get the current time
        final Calendar c = Calendar.getInstance();
        mHour = c.get(Calendar.HOUR_OF_DAY);
        mMinute = c.get(Calendar.MINUTE);

        // display the current date
        updateDisplay1();

First, the content is set to the main.xml layout and then the TextView and Button are captured with findViewById(int)and & when the Button is clicked TimePickerDialog is displayed A new Calendar is created to get the current hour and minute. Finally, the private updateDisplay1() method is called in order to fill the TextView with the current time.

d)Add the updateDisplay1() and pad() methods:

// updates the time we display in the TextView
private void updateDisplay1() {
    mTimeDisplay.setText(
        new StringBuilder()
                .append(pad(mHour)).append(":")
                .append(pad(mMinute)));
}

private static String pad(int c) {
    if (c >= 10)
        return String.valueOf(c);
    else
        return "0" + String.valueOf(c);
}

The updateDisplay() method uses the member fields for the time and inserts them in the mTimeDisplay TextView. The pad() method returns the appropriate string representation of the hour or minute—it will prefix a zero to the number if it’s a single digit.

e) Add a class member for a TimePickerDialog.OnTimeSetListener that will be called when the user sets a new

time:

// the callback received when the user "sets" the time in the dialog
private TimePickerDialog.OnTimeSetListener mTimeSetListener =
    new TimePickerDialog.OnTimeSetListener() {
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            mHour = hourOfDay;
            mMinute = minute;
            updateDisplay();
        }
    };

When the user is done setting the time (clicks the “Set” button), the onTimeSet() method is called and it updates the member fields with the new time and updates the layout’s TextView.

f) Run the application

7)Download sourcecode:
Click here to download source code.

AUTHOR: Vikas Hiran
No Comments

Leave a Comment

Your email address will not be published.