Để tạo ra các thông báo và lựa chọn có rất nhiều loại Dialog, trong đó có 3 loại Dialog thông dụng là:
- DatePickerDialog.
- TimePickerDialog.
- ProgressDialog.
DatePickerDialog
DatePickerDialog
là dạng Dialog của Android cho phép chọn ngày, tháng, năm trên Dialog đó.

Việc sử dụng rất đơn giản, chỉ cần khởi tạo đối tượng DatePickerDialog
với constructor:
public DatePickerDialog(Context context, DatePickerDialog.OnDateSetListener listener, int year, int month, int dayOfMonth)
Với các đối số lần lượt là
context
: context màDatePickerDialog
sử dụng.listener
: lắng nghe sự kiện khi nhấn OK trên Dialog.year
,month
,dayOfMonth
: năm, tháng, ngày hiển thị trên Dialog.
Ví dụ:
Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH); int day = calendar.get(Calendar.DAY_OF_MONTH); DatePickerDialog datePickerDialog = new DatePickerDialog(MainActivity.this, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { } }, year, month, day);
- Phương thức
show()
để hiển thị Dialog:datePickerDialog.show();
- Phương thức
dismiss()
để tắt Dialog:datePickerDialog.dismiss();
TimePickerDialog
Cũng giống như DatePickerDialog
cũng là 1 dạng Dialog hệ thống nhưng thay vì chọn ngày, tháng, năm thì TimePickerDialog
dùng để chọn thời gian (giờ, phút, giây).

Việc sử dụng TimePickerDialog
hoàn toàn giống như DatePickerDialog
, constructor truyền vào là context
, listener
, hour
, minute
, is24ViewHour
.
public TimePickerDialog(Context context, OnTimeSetListener listener, int hourOfDay, int minute, boolean is24HourView)
Ví dụ:
Calendar calendar = Calendar.getInstance(); final int hour = calendar.get(Calendar.HOUR_OF_DAY); int minute = calendar.get(Calendar.MINUTE); TimePickerDialog timePickerDialog = new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { Log.e(TAG, "onTimeSet: " + hour + ", " + minute); } }, hour, minute, true); timePickerDialog.show();
Tương tự cũng phải gọi phương thức show()
và dismiss()
, nếu muốn hiển thị hoặc đóng Dialog.
Cả hai ví dụ với DatePickerDialog
và TimePickerDialog
, đều sử dụng Calendar
để lấy về ngày và thời gian hiện tại và hiển thị lên 2 loại Dialog này.
ProgressDialog
ProgressDialog
là Dialog thường dùng, để hiển thị thông báo khi đang tải về, cần thông báo cho người dùng chờ đợi trong giây lát.
Ví dụ:
ProgressDialog progressDialog = new ProgressDialog(MainActivity.this); progressDialog.setTitle("Loading..."); progressDialog.setMessage("Please waiting..."); progressDialog.show();
Và khi nào hoàn thành công việc, phải gọi phương thức dismiss()
để đóng Dialog.
ProgressDialog
hay được sử dụng kết hợp với AsyncTask
Hiển thị Dialog trước khi vào chạy phương thức doInBackground()
trong onPreExcute()
và dismiss()
Dialog, sau khi doInBackground()
thực hiện xong trong phương thức onPostExcute()
.