Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 236
Ahmed Avatar asked Feb 07 '12 21:02

Ahmed


3 Answers

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);.

like image 177
Jacob Marble Avatar answered Oct 04 '22 16:10

Jacob Marble


Presumably you want to detect a touch event anywhere within the bounds of a dialog. If you're creating a custom dialog (i.e. by assembling a set of Views into a layout View of some sort, and then setting the parent View as the dialog's main content view using .setContentView()) then perhaps you could simply set an onTouch listener to that content parent View. Furthermore, you could grab hold of views using mDialog.findViewById(), so if for example you were using an AlertDialog, perhaps you could determine somehow what resource ID to use to grab hold of its main layout View.

like image 21
Trevor Avatar answered Oct 04 '22 16:10

Trevor


If you have a Layout in your Dialog, you could get a reference to that as view, and put a onClickListener on that. So assuming your dialog has a custom layout, and view for the entire dialog, get a reference to that.

For instance, assuming a dialog has a LinearLayout named mainll, that contains your custom views, you would:

LinearLayout ll - (LinearLayout) findViewById(R.id.mainll);
ll.setOnClickListener(...) { onClick()... }

Then anytime anything is clicked within the LinearLayout, it will register a click event.

like image 23
Booger Avatar answered Oct 04 '22 16:10

Booger