A dialog is a small window that prompts the user to make a decision or enter additional information. A dialog does not fill the screen and is normally used for modal events that require users to take an action before they can proceed.
The Dialog class is the base class for dialogs.
Activities provide a facility to manage the creation, saving and restoring of dialogs via methods onCreateDialog(), onPrepareDialog, showDialog, and dismissDialog()methods. But at nowdays DialogFragment is used.
There are built-in dialogs:
AlertDialog - can show a title, up to three buttons, a list of selectable items, or a custom layout. You can create dialog with AlertDialog.Builder class.
DatePickerDialog - allows to select date.
TimePickerDialog - allows to select time.
DialogFragment is a special fragment, that can be shown as a dialog window or embedded into UI as normal fragment. For example, on a small screen you can show it as embedded and on a large screen as dialog.
// show as dialog
DialogFragment newFragment = MyDialogFragment.newInstance();
newFragment.show(getFragmentManager(), "dialog");
Use fragment manager to dissmiss dialog from activity.
find and close dialog
fun showOrHideSpinnerProgress(isShow: Boolean) {
val dlg = supportFragmentManager.findFragmentByTag(TAG_SPINNER_PROGRESS_DIALOG)
if (isShow) {
if (dlg != null) return // dialog already shown
ProgrogressSpinnerDialogFragment().show(
supportFragmentManager,
TAG_SPINNER_PROGRESS_DIALOG
)
} else {
if (dlg is ProgrogressSpinnerDialogFragment) {
dlg.dismiss()
}
}
}
You can also use the dismiss() method to close the dialog from the inside, for example in response to a button click.
You can create a dialog object in DialogFragment, for example using AlertDialog.Builder. In this case, the fragment can only be shown as a dialog and not as an embedded fragment.
AlertDialog example
class FireMissilesDialogFragment : DialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle): Dialog {
return activity?.let {
// Use the Builder class for convenient dialog construction
val builder = AlertDialog.Builder(it)
builder.setMessage(R.string.dialog_fire_missiles)
.setPositiveButton(R.string.fire,
DialogInterface.OnClickListener { dialog, id ->
// FIRE ZE MISSILES!
})
.setNegativeButton(R.string.cancel,
DialogInterface.OnClickListener { dialog, id ->
// User cancelled the dialog
})
// Create the AlertDialog object and return it
builder.create()
} ?: throw IllegalStateException("Activity cannot be null")
}
}
public class FireMissilesDialogFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.dialog_fire_missiles)
.setPositiveButton(R.string.fire, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// FIRE ZE MISSILES!
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
AlertDialog
AlertDialog can show dialog box with up to three buttons, a list of selectable items, or a custom layout.
Use the setCanceledOnTouchOutside(true) method to allow the dialog to close when the user clicks outside the dialog.
Use AlertDialog.Builder class to build AlertDialog.
AlertDialog single-choice list example
class ColorSelectDialog : DialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return activity?.let {
val builder = AlertDialog.Builder(it)
builder.setTitle(R.string.pick_color)
// use setAdapter() if items are provided via Adapter
.setItems(R.array.colors_array,
DialogInterface.OnClickListener { dialog, which ->
// The 'which' argument contains the index position
// of the selected item
})
builder.create()
} ?: throw IllegalStateException("Activity cannot be null")
}
}
public static class ColorSelectDialog extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.pick_color)
// use setAdapter() if items are provided via Adapter
.setItems(R.array.colors_array, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
}
});
return builder.create();
}
}
AlertDialog multiple-choice list example
class ItemsSelectDialog : DialogFragment(){
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return activity?.let {
val selectedItems = ArrayList<Int>() // Where we track the selected items
val builder = AlertDialog.Builder(it)
// Set the dialog title
builder.setTitle(R.string.pick_toppings)
// Specify the list array, the items to be selected by default (null for none),
// and the listener through which to receive callbacks when items are selected
.setMultiChoiceItems(R.array.toppings, null,
DialogInterface.OnMultiChoiceClickListener { dialog, which, isChecked ->
if (isChecked) {
// If the user checked the item, add it to the selected items
selectedItems.add(which)
} else if (selectedItems.contains(which)) {
// Else, if the item is already in the array, remove it
selectedItems.remove(which)
}
})
// Set the action buttons
.setPositiveButton(R.string.ok,
DialogInterface.OnClickListener { dialog, id ->
// User clicked OK, so save the selectedItems results somewhere
// or return them to the component that opened the dialog
...
})
.setNegativeButton(R.string.cancel,
DialogInterface.OnClickListener { dialog, id ->
...
})
builder.create()
} ?: throw IllegalStateException("Activity cannot be null")
}
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
selectedItems = new ArrayList(); // Where we track the selected items
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Set the dialog title
builder.setTitle(R.string.pick_toppings)
// Specify the list array, the items to be selected by default (null for none),
// and the listener through which to receive callbacks when items are selected
.setMultiChoiceItems(R.array.toppings, null,
new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
if (isChecked) {
// If the user checked the item, add it to the selected items
selectedItems.add(which);
} else if (selectedItems.contains(which)) {
// Else, if the item is already in the array, remove it
selectedItems.remove(which);
}
}
})
// Set the action buttons
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
// User clicked OK, so save the selectedItems results somewhere
// or return them to the component that opened the dialog
...
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
...
}
});
return builder.create();
}
TimePickerDialog
TimePickerDialog example
class TimePickerFragment : DialogFragment(), TimePickerDialog.OnTimeSetListener {
override fun onCreateDialog(savedInstanceState: Bundle): Dialog {
// Use the current time as the default values for the picker
val c = Calendar.getInstance()
val hour = c.get(Calendar.HOUR_OF_DAY)
val minute = c.get(Calendar.MINUTE)
// Create a new instance of TimePickerDialog and return it
return TimePickerDialog(activity, this, hour, minute, DateFormat.is24HourFormat(activity))
}
override fun onTimeSet(view: TimePicker, hourOfDay: Int, minute: Int) {
// Do something with the time chosen by the user
}
}
// show in activity
// TimePickerFragment().show(supportFragmentManager, "timePicker")
public static class TimePickerFragment extends DialogFragment
implements TimePickerDialog.OnTimeSetListener {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// Do something with the time chosen by the user
}
}
// show in activity
// DialogFragment newFragment = new TimePickerFragment();
// newFragment.show(getSupportFragmentManager(), "timePicker");
DatePickerDialog
DatePickerDialog example
class DatePickerFragment : DialogFragment(), DatePickerDialog.OnDateSetListener {
override fun onCreateDialog(savedInstanceState: Bundle): Dialog {
// Use the current date as the default date in the picker
val c = Calendar.getInstance()
val year = c.get(Calendar.YEAR)
val month = c.get(Calendar.MONTH)
val day = c.get(Calendar.DAY_OF_MONTH)
// Create a new instance of DatePickerDialog and return it
return DatePickerDialog(activity, this, year, month, day)
}
override fun onDateSet(view: DatePicker, year: Int, month: Int, day: Int) {
// Do something with the date chosen by the user
}
}
// show in activity
// val newFragment = DatePickerFragment()
// newFragment.show(supportFragmentManager, "datePicker")
public static class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
}
}
// show in activity
// DialogFragment newFragment = new DatePickerFragment();
// newFragment.show(getSupportFragmentManager(), "datePicker");