[android] How to dismiss the dialog with click on outside of the dialog?

I have implemented a custom dialog for my application. I want to implement that when the user clicks outside the dialog, the dialog will be dismissed. What do I have to do for this?

The answer is


Simply use

dialog.setCanceledOnTouchOutside(true);

Following has worked for me:

myDialog.setCanceledOnTouchOutside(true);

Here is the code

    dialog.getWindow().getDecorView().setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent ev) {

            if(MotionEvent.ACTION_DOWN == ev.getAction())
            {
                Rect dialogBounds = new Rect();
                dialog. getWindow().getDecorView().getHitRect(dialogBounds);
                if (!dialogBounds.contains((int) ev.getX(), (int) ev.getY())) {
                    // You have clicked the grey area
                    UiUtils.hideKeyboard2(getActivity());
                    return false; // stop activity closing
                }
            }
            getActivity().dispatchTouchEvent(ev);
            return false;
        }
    });

Try this one . you can hide the keyboard when you touch outside


This code is use for when use click on dialogbox that time hidesoftinput and when user click outer side of dialogbox that time both softinput and dialogbox are close.

dialog = new Dialog(act) {
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // Tap anywhere to close dialog.
        Rect dialogBounds = new Rect();
        getWindow().getDecorView().getHitRect(dialogBounds);
        if (!dialogBounds.contains((int) event.getX(),
                (int) event.getY())) {
            // You have clicked the grey area
            InputMethodManager inputMethodManager = (InputMethodManager) act
                    .getSystemService(act.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(dialog
                    .getCurrentFocus().getWindowToken(), 0);
            dialog.dismiss();
            // stop activity closing
        } else {
            InputMethodManager inputMethodManager = (InputMethodManager) act
                    .getSystemService(act.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(dialog
                    .getCurrentFocus().getWindowToken(), 0);
        }

        return true;
    }
};

Call dialog.setCancelable(false); from your activity/fragment.


dialog.setCanceledOnTouchOutside(true); 

to close dialog on touch outside.

And if you don't want to close on touch outside, use the code below:

dialog.setCanceledOnTouchOutside(false);

Or, if you're customizing the dialog using a theme defined in your style xml, put this line in your theme:

<item name="android:windowCloseOnTouchOutside">true</item>

You can make a background occupying all the screen size transparent and listen to the onClick event to dismiss it.


You can try this :-

AlterDialog alterdialog;
alertDialog.setCanceledOnTouchOutside(true);

or

alertDialog.setCancelable(true);

And if you have a AlterDialog.Builder Then you can try this:-

alertDialogBuilder.setCancelable(true);

Another solution, this code was taken from android source code of Window You should just add these Two methods to your dialog source code.

@Override
public boolean onTouchEvent(MotionEvent event) {        
    if (isShowing() && (event.getAction() == MotionEvent.ACTION_DOWN
            && isOutOfBounds(getContext(), event) && getWindow().peekDecorView() != null)) {
        hide();
    }
    return false;
}

private boolean isOutOfBounds(Context context, MotionEvent event) {
    final int x = (int) event.getX();
    final int y = (int) event.getY();
    final int slop = ViewConfiguration.get(context).getScaledWindowTouchSlop();
    final View decorView = getWindow().getDecorView();
    return (x < -slop) || (y < -slop)
            || (x > (decorView.getWidth()+slop))
            || (y > (decorView.getHeight()+slop));
}

This solution doesnt have this problem :

This works great except that the activity underneath also reacts to the touch event. Is there some way to prevent this? – howettl


This method should completely avoid activities below the grey area retrieving click events.

Remove this line if you have it:

window.setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL, WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);

Put this on your activity created

getWindow().setFlags(LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH, LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);

then override the touch event with this

@Override
public boolean onTouchEvent(MotionEvent ev)
{
    if(MotionEvent.ACTION_DOWN == ev.getAction())
    {
        Rect dialogBounds = new Rect();
        getWindow().getDecorView().getHitRect(dialogBounds);
        if (!dialogBounds.contains((int) ev.getX(), (int) ev.getY())) {
            // You have clicked the grey area
            displayYourDialog();
            return false; // stop activity closing
        }
    }

    // Touch events inside are fine.
    return super.onTouchEvent(ev);
}

You can use this implementation of onTouchEvent. It prevent from reacting underneath activity to the touch event (as mentioned howettl).

@Override
public boolean onTouchEvent ( MotionEvent event ) {
  // I only care if the event is an UP action
  if ( event.getAction () == MotionEvent.ACTION_UP ) {
    // create a rect for storing the window rect
    Rect r = new Rect ( 0, 0, 0, 0 );
    // retrieve the windows rect
    this.getWindow ().getDecorView ().getHitRect ( r );
    // check if the event position is inside the window rect
    boolean intersects = r.contains ( (int) event.getX (), (int) event.getY () );
    // if the event is not inside then we can close the activity
    if ( !intersects ) {
      // close the activity
      this.finish ();
      // notify that we consumed this event
      return true;
    }
  }
  // let the system handle the event
  return super.onTouchEvent ( event );
}

Source: http://blog.twimager.com/2010/08/closing-activity-by-touching-outside.html


Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to android-layout

How to check if a key exists in Json Object and get its value How to center the elements in ConstraintLayout Android - how to make a scrollable constraintlayout? Add ripple effect to my button with button background color? This view is not constrained vertically. At runtime it will jump to the left unless you add a vertical constraint Is it possible to put a ConstraintLayout inside a ScrollView? Differences between ConstraintLayout and RelativeLayout How to remove title bar from the android activity? How to have EditText with border in Android Lollipop Android: ScrollView vs NestedScrollView

Examples related to android-emulator

flutter run: No connected devices How to remove the Flutter debug banner? Android Studio AVD - Emulator: Process finished with exit code 1 Android Studio Emulator and "Process finished with exit code 0" Run react-native on android emulator ERROR Android emulator gets killed Error while waiting for device: Time out after 300seconds waiting for emulator to come online Unfortunately Launcher3 has stopped working error in android studio? updating Google play services in Emulator Android Studio emulator does not come with Play Store for API 23

Examples related to dialog

Disable click outside of angular material dialog area to close the dialog (With Angular Version 4.0+) How to change DatePicker dialog color for Android 5.0 Android simple alert dialog Swift alert view with OK and Cancel: which button tapped? How to make a edittext box in a dialog How to check if activity is in foreground or in visible background? jquery ui Dialog: cannot call methods on dialog prior to initialization JavaScript: Create and save file Prevent Android activity dialog from closing on outside touch How to use OpenFileDialog to select a folder?

Examples related to android-dialog

How to make custom dialog with rounded corners in android How to create a number picker dialog? How to create a Custom Dialog box in android? How to set DialogFragment's width and height? Dialog with transparent background in Android How to dismiss the dialog with click on outside of the dialog? Android DialogFragment vs Dialog Android 'Unable to add window -- token null is not for an application' exception Show dialog from fragment? Android 1.6: "android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application"