> Note: The system calls onDismiss()
upon each event that invokes the onCancel()
callback. However, if you call Dialog.dismiss()
or DialogFragment.dismiss()
, the system calls onDismiss()
but notonCancel()
. So you should generally call dismiss()
when the user presses the positive button in your dialog in order to remove the dialog from view.
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); // Add the buttons builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User clicked OK button } }); builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User cancelled the dialog } }); // Set other dialog properties ... // Create the AlertDialog AlertDialog dialog = builder.create();
And here's some code that decides whether to show the fragment as a dialog or a fullscreen UI, based on the screen size:
public void showDialog() { FragmentManager fragmentManager = getSupportFragmentManager(); CustomDialogFragment newFragment = new CustomDialogFragment(); if (mIsLargeLayout) { // The device is using a large layout, so show the fragment as a dialog newFragment.show(fragmentManager, "dialog"); } else { // The device is smaller, so show the fragment fullscreen FragmentTransaction transaction = fragmentManager.beginTransaction(); // For a little polish, specify a transition animation transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); // To make it fullscreen, use the 'content' root view as the container // for the fragment, which is always the root view for the activity transaction.add(android.R.id.content, newFragment) .addToBackStack(null).commit(); } }