Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tap outside Android dialog to dismiss it?

I was wondering if it's possible to somehow tap outside a popup dialog (or an Activity with a dialog theme), and dismiss it by just tapping outside of it?

I made a quick picture to illustrate it:

enter image description here

Normally, you have to press the back key to dismiss the dialogs, but on Honeycomb it could be great to have the option of just tapping outside the dialog, due to all the screen estate.

like image 660
Michell Bak Avatar asked Aug 27 '11 11:08

Michell Bak


People also ask

How do you dismiss dialog with click on outside of dialog?

You can use dialog. setCanceledOnTouchOutside(true); which will close the dialog if you touch outside of the dialog.

How do I stop dialog close on click outside Android?

Simply, alertDialog. setCancelable(false); prevent user from click outside of Dialog Box.

How do you dismiss material dialog?

setCancelable(false); AlertDialog dialog = builder. show(); In order to dismiss the dialog, you can call dismiss function like this.

How do you dismiss a DialogFragment?

tl;dr: The correct way to close a DialogFragment is to use dismiss() directly on the DialogFragment. Control of the dialog (deciding when to show, hide, dismiss it) should be done through the API here, not with direct calls on the dialog.


2 Answers

My app is a single activity with Theme.Holo.Dialog. In my case the other answer did not work. It only made the other background apps or the launch screen to receive touch events.

I found that using dispatchTouchEvent works in my case. I think it is also a simpler solution. Here's some sample code on how to use it to detect taps outside the activity with a Dialog theme:

@Override public boolean dispatchTouchEvent(MotionEvent ev) {     Rect dialogBounds = new Rect();     getWindow().getDecorView().getHitRect(dialogBounds);      if (!dialogBounds.contains((int) ev.getX(), (int) ev.getY())) {         // Tapped outside so we finish the activity         this.finish();     }     return super.dispatchTouchEvent(ev); } 
like image 37
Jan S. Avatar answered Sep 22 '22 22:09

Jan S.


dialog.setCanceledOnTouchOutside(true)  

Sets whether this dialog is canceled when touched outside the window's bounds.

like image 171
Francesco Vadicamo Avatar answered Sep 21 '22 22:09

Francesco Vadicamo