How to dismiss a Dialog in Android by clicking it inside?

Ahmed picture Ahmed · Feb 7, 2012 · Viewed 8.9k times · Source

I have seen several posts on how to dismiss a dialog by clicking on the outside. But is there a way to get the same functionality by clicking the inside the dialog window?

Are there any listeners for the Dialog that would detect a tap on the Dialog Window?

Answer

Jacob Marble picture Jacob Marble · Apr 1, 2012

Overriding Dialog.onTouchEvent(...) catches any tap, anywhere on the screen. To dismiss the dialog by tapping anywhere:

Dialog dialog = new Dialog(this) {
  @Override
  public boolean onTouchEvent(MotionEvent event) {
    // Tap anywhere to close dialog.
    this.dismiss();
    return true;
  }
};

This snippet nullifies the need to call dialogObject.setCanceledOnTouchOutside(true);.