Dismiss DialogFragment(not Dialog) onTouchOutside

C.d. picture C.d. · Jan 4, 2012 · Viewed 14.5k times · Source

I have searched through all the answers about dismissing a Dialog onTouchOutside, however, I am using DialogFragment in my application. How can I achieve dismissing the DialogFragment when user clicks outside the DialogFragment's region.

I have examined Dialog's source code for setCanceledOnTouchOutside

public void setCanceledOnTouchOutside(boolean cancel) {
    if (cancel && !mCancelable) {
        mCancelable = true;
    }

    mCanceledOnTouchOutside = cancel;
}

There's another function which may be interesting which is isOutOfBounds

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

but I couldn't figure out a way to make use of these for DialogFragment

In addition to these I have examined the state of the application with hierarchyviewer and as I understand it, I can only see the region of the dialog and not the outsied part of it (I mean the remaining part of the screen after the DialogFragment).

Can you suggest a way of implementing this setCanceledOnTouchOutside for DialogFragment and if possible with a sample code?

Answer

Fenix Voltres picture Fenix Voltres · Feb 14, 2012

The answer is pretty simple:

MyDialogFragment fragment = new MyDialogFragment(); // init in onCreate() or somewhere else
...
if ( fragment.getDialog() != null )
    fragment.getDialog().setCanceledOnTouchOutside(true); // after fragment has already dialog, i. e. in onCreateView()

See http://developer.android.com/reference/android/app/DialogFragment.html#setShowsDialog%28boolean%29 for more info about dialogs in DialogFragments.