
Editorial illustration.
Originally published 26 June 2023; rewritten and reviewed on 15 October 2026.
Showing a confirmation dialog in Android looks trivial on paper—until a user rotates their phone, taps the “Delete” button twice in quick succession, or switches to WhatsApp to check a message while the dialog is still open. If you built that modal by calling new Dialog(this) directly inside an Activity, you quickly run into vanished dialogs, duplicate API calls, or the infamous WindowLeaked crash in Logcat.
A modal dialog is not just a floating XML layout. It is a piece of UI state that needs a clear lifecycle owner, a clean way to return its result, and guardrails against impatient tapping.
Use DialogFragment so rotation does not destroy your dialog
The oldest mistake in Android Java tutorials is instantiating AlertDialog or Dialog directly in a button’s OnClickListener without tying it to the FragmentManager. When the screen rotates, Android destroys and recreates the Activity. A raw Dialog does not survive that recreation—it either disappears silently or crashes with Activity has leaked window DecorView.
Wrapping your modal inside an AppCompatDialogFragment (or DialogFragment) lets the FragmentManager automatically save and restore the dialog across configuration changes. Keep the decision explicit: use clear action verbs like “Delete invoice” and “Keep” rather than vague “Yes” and “No” buttons, so a user returning from another app immediately knows what they are confirming.
public class DeleteItemDialogFragment extends DialogFragment {
public static final String REQUEST_KEY = "delete_item_request";
public static final String RESULT_CONFIRMED = "confirmed";
private static final String ARG_ITEM_NAME = "item_name";
public static DeleteItemDialogFragment newInstance(String itemName) {
DeleteItemDialogFragment fragment = new DeleteItemDialogFragment();
Bundle args = new Bundle();
args.putString(ARG_ITEM_NAME, itemName);
fragment.setArguments(args);
return fragment;
}
@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
String itemName = requireArguments().getString(ARG_ITEM_NAME, "this item");
return new MaterialAlertDialogBuilder(requireContext())
.setTitle("Delete " + itemName + "?")
.setMessage("This action removes the record permanently and cannot be undone.")
.setPositiveButton("Delete", (dialog, which) -> {
Bundle result = new Bundle();
result.putBoolean(RESULT_CONFIRMED, true);
getParentFragmentManager().setFragmentResult(REQUEST_KEY, result);
})
.setNegativeButton("Cancel", null)
.create();
}
}
Notice two details here. First, data enters the fragment via Bundle arguments (newInstance), never via a custom constructor—because Android calls the zero-argument constructor when recreating fragments after process death or rotation. Second, requireContext() is used inside onCreateDialog instead of caching an Activity reference in a static field.
Return results via Fragment Result API, not direct Activity casts
Earlier Java codebases often defined an interface and cast (MyActivity) getActivity() inside the dialog. That couples your dialog to one specific Activity and breaks immediately if you later host the flow inside a Fragment or bottom navigation tab.
Using getParentFragmentManager().setFragmentResult(...) keeps the dialog decoupled. In your host Activity or parent Fragment, register the listener in onCreate:
getSupportFragmentManager().setFragmentResultListener(
DeleteItemDialogFragment.REQUEST_KEY,
this,
(requestKey, result) -> {
if (result.getBoolean(DeleteItemDialogFragment.RESULT_CONFIRMED, false)) {
viewModel.deleteSelectedItem();
}
}
);
This also survives configuration changes cleanly because FragmentManager delivers the result only when the host reaches STARTED state.
Prevent double-opening and duplicate submissions
On slower mid-range phones, a user who taps a button twice within 200 milliseconds can trigger dialog.show(...) twice—stacking two identical dialogs on top of each other—or fire two DELETE network requests before the UI updates.
Before showing the dialog, check whether a fragment with the same tag is already attached to the FragmentManager:
private static final String TAG_DELETE_DIALOG = "delete_dialog";
private void showDeleteConfirmation(String itemName) {
FragmentManager fm = getSupportFragmentManager();
if (fm.findFragmentByTag(TAG_DELETE_DIALOG) != null) {
return;
}
DeleteItemDialogFragment.newInstance(itemName).show(fm, TAG_DELETE_DIALOG);
}
Inside the host’s result handler, disable the trigger button or set an isDeleting flag in your ViewModel while the network call is in flight. Do not show a “Deleted” toast inside the dialog’s positive click listener; wait until the backend actually returns HTTP 200.
Check dismissal rules, custom layouts, and accessibility
If your dialog contains a text input—say, asking for a cancellation reason—wrap the custom XML layout in a ScrollView so it remains usable on smaller screens when the soft keyboard opens or when the user enables large system font sizes. Never assume a fixed-height ConstraintLayout will fit once TalkBack or 1.3x font scaling is active.
Finally, decide intentionally whether tapping outside the dialog or pressing the system Back button should cancel the action. For destructive confirmations, leaving default cancellation enabled is usually right because cancelling is safe. If you do set setCancelable(false) during a blocking step, always give the user a clear way out so they never feel trapped on a frozen overlay. And if a modal starts needing multiple form fields, validation errors, and progress spinners, skip the dialog altogether and move it to a dedicated screen.