Search code examples
androidandroid-dialogfragmentandroid-dialog

How do we know how exactly user cancelled the dialog?


I use a cancellable dialog fragment with setCanceledOnTouchOutside(true). Now I want to distinguish two cases:

  • user cancels the dialog using Back button;
  • user cancels the dialog by touching outside of it.

Both actions lead to invocation of both onCancel() and onDismiss() listeners. Also these two listeners accept DialogInterface as a parameter, to there no any "event state" to check how exactly user has cancelled the dialog.

So what can I do?


Solution

  • To know if the user has pressed the back button of the device, override the method onBackPressed:

    @Override
    public void onBackPressed()
    {
     //here you could set a boolean to know if the user pressed the back button, and react accordingly when the dialog is closed.
    backPressed=true;
    }
    

    For example.