45

Say I have a created a dialog in my Android app like so:

private static ProgressDialog dialog;
dialog = ProgressDialog.show(MainActivity.this, "", "Downloading Files. Please wait...", true);

Now, is it possible to fire an event when the following is called?

dialog.dismiss();

The reason I want to do this and not just call my method after dialog.dismiss(); is because the Dialog dismiss is called within a static class and the next thing I want to do is load a new Activity (which cannot be done using Intents within a static class).

ingh.am
  • 25,981
  • 43
  • 130
  • 177

6 Answers6

69

Use an OnDismissListener.

There is a setOnDismissListener(...) method in the class Dialog

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
Aleadam
  • 40,203
  • 9
  • 86
  • 108
  • 6
    Warning, this approach is incompatible with DialogFragments as of API 11. See [DialogFragment.onCreateDialog()](http://developer.android.com/reference/android/app/DialogFragment.html#onCreateDialog(android.os.Bundle)) – RonR Apr 12 '14 at 19:40
  • @Mahan did you find any alternative for this? Thanks – sandeepmaaram Aug 08 '17 at 07:31
  • Note that this doesn't work if the user clicks on Home button - in such case, the solution I found was to listen to when the activity which created the dialog has been dismissed. – Yoav Feuerstein Oct 19 '17 at 11:23
11

Sure you can - check:

  public void onDismiss(DialogInterface dialogInterface)
  {
        //Fire event
  }
Barmaley
  • 16,638
  • 18
  • 73
  • 146
8

Whenever a dialog is closed either by clicking PositiveButton, NegativeButton, NeturalButton or by clicking outside of the dialog, "onDismiss" is always gets called automatically so do your stuff inside the onDismiss() method e.g.,

@Override
public void onDismiss(DialogInterface dialogInterface) {
    ...
}

You don't even need to call dismiss() method.

Rahim
  • 799
  • 6
  • 7
5

Use setOnDismissListener method for the dialog.

dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
    @Override
    public void onDismiss(DialogInterface dialog) {
        if (mIsSettingsDirty)
            refreshRecyclerView();
    }
});
live-love
  • 48,840
  • 22
  • 240
  • 204
2

If you are within custom dialog class - override dismiss(). I recommend inserting logic BEFORE super.dismiss(). Kotlin example:

override fun dismiss() {
    Utils.hideKeyboard(mContext, window)
    super.dismiss()
}
SilverTech
  • 399
  • 4
  • 11
0

If you want handle Dialog hiding, you can override 2 methods.

    @Override
    public void cancel() {
        super.cancel();
        callback();
    }

    @Override
    public void dismiss() {
        super.dismiss();
        callback();
    }
Vlad
  • 7,997
  • 3
  • 56
  • 43