Thursday, 23 January 2020

Android: how to dismiss a DatePicker DialogFragment when touching outside?

I have a working DatePickerFragment that extends DialogFragment. I set up a DatePickerDialog in onCreateDialog() and then tried to add:

"picker.setCanceledOnTouchOutside(true);"

I am testing on a device with Android 8.0 Oreo and nothing happens when touching outside the DatePicker dialog. I am using androidx.appcompat.app.AppCompatActivity as my BaseActivity and androidx.fragment.app.DialogFragment for the DialogFragment;

Code:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    super.onCreateDialog(savedInstanceState);

    DatePickerDialog picker = new DatePickerDialog(getActivity(),this,year,month,day);
    **picker.setCanceledOnTouchOutside(true);**
    return picker;

This is the Activity code that creates the Fragment:

DatePickerFragment newFragment = new DatePickerFragment();
// tried the below also, with no luck
**newFragment.setCancelable(true);**
newFragment.show(getSupportFragmentManager(), "datePicker");

I also tried the below in the DialogFragment, also with no luck:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
   ...
   getDialog().setCanceledOnTouchOutside(true);
   ... 
   }

and:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    if (getDialog() != null) {
        getDialog().setCanceledOnTouchOutside(true);
    }
    return super.onCreateView(inflater, container, savedInstanceState);
}    

I referenced this post for possible answers: How to dismiss a DialogFragment when pressing outside the dialog?. What am I missing here?



from Android: how to dismiss a DatePicker DialogFragment when touching outside?

No comments:

Post a Comment