Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dismiss DialogFragment(not Dialog) onTouchOutside

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?

like image 704
C.d. Avatar asked Jan 04 '12 21:01

C.d.


2 Answers

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.

like image 128
Fenix Voltres Avatar answered Oct 11 '22 08:10

Fenix Voltres


In most cases, getDialog() is null, since you won't get it immediately after you make a new instance of your dialog.

As suggested above onViewCreated is also nor correct for DialogFragment especially when using android.support.v4.app.DialogFragment.

The below works well, as it's placed on the onCreateView:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    if (getDialog() != null) {
        getDialog().setCanceledOnTouchOutside(true);
    }
    return super.onCreateView(inflater, container, savedInstanceState);
}
like image 27
ericosg Avatar answered Oct 11 '22 07:10

ericosg