I have defined a method for my DialogFragment which will pop another (alert) dialog, where I confirm that the user wants to dismiss the DialogFragment. If that is the case, then I call DialogFragment.dismiss()
. If not, the dismissal of the DialogFragment should simply be ignored and the user should return to it as was before.
This method (say, confirmCancel()
) is used for the 'Cancel' button at the bottom of the DialogFragment. Since I also want this to appear when the user presses the back button, or when they touch outside the DialogFragment, I have set confirmCancel as its onCancelListener
(of course, I have also used getDialog().setCanceledOnTouchOutside(true)
too).
This is the code for confirmCancel()
:
public void confirmCancel()
{
(new AlertDialog.Builder(getActivity())
.setIcon(R.drawable.ic_baseline_warning_24)
.setTitle("Discard changes")
.setMessage("Are you sure you want to discard changes and go back?")
.setPositiveButton("Yes", ( dialogInterface, i ) -> dismiss())
.setNegativeButton("No", ( dialogInterface, i ) -> {})
.show()).setCanceledOnTouchOutside(true);
}
This works almost perfectly, except for the fact that by the time the AlertDialog is shown on screen, the DialogFragment is already dismissed, and the actions taken in the AlertDialog are of no use at all.
So what I need now is a way to 'cancel' the dismissal of the DialogFragment, or a method that is called before the its dismissal. How do I solve this?
P.S.: getDialog().setCancelable(false)
is not helpful to me since I do want the dialog to be cancelled; it's just that I want it cancelled conditionally.