onBackpressed DialogFragment

user3621165 picture user3621165 · Jul 27, 2014 · Viewed 7.1k times · Source

I have 3 custom dialogs (DialogFragment). All are not cancelable, because it is necessary, that the user can't close them. The first dialog starts the second, and the second the third. Now I want to came back to the previous dialog, if I'm using the backclick. At this moment I have two options, but both are not work's really fine:

  • I start from one dialog the new one, but never call the dismiss. -> So in the background of the next dialog is always the view of the previous dialog

  • I call dismiss, if I'm start the next dialog, but then he will not return to the previous dialog, but close the dialog.

What can I do, to start the new dialog, so, that the first one is not visible, but if I'm click back, the dialog is visible again?

Thanks a lot for help :))

Answer

Bojan Kopanja picture Bojan Kopanja · Jul 27, 2014

When you advance from second dialog to third you can close the second one so that you don't see it in the third one.

Later if you need to go back to the second dialog you can re-start it just before closing the third one, the same way you start it when you go from the first dialog to second dialog.

In order to override onBackPressed of a dialog you need to do something like this:

dialog.setOnCancelListener(new DialogInterface.OnCancelListener()
{
    @Override
    public void onCancel(DialogInterface dialog)
    {
        // OVERRIDE CODE
    }
});

so the work flow would be something like this

  1. firstDialog -> startSecondDialog
  2. firstDialog.dismiss
  3. secondDialog -> startThirdDialog
  4. secondDialog.dismiss

and then if you need to go back you do:

  1. thirdDialog -> startSecondDialog
  2. thirdDialog.dismiss

and so on until you get back to the first dialog.

I hope this makes sense to you, and if not please give us some code so we can help with more details related to your project :)