Dismiss DatePickerDialog on pressing back button

后端 未结 8 1945
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-19 12:29

On my view I have a button which when pressed pops up a DatePickerDialog. The poppedup dialog has a \"Done\" button. When I press that button the selected date is populated

8条回答
  •  一向
    一向 (楼主)
    2020-12-19 12:48

    I wrote simple successor of standard DatePickerDialog that works fine for me:

    /**
     * Enhanced date picker dialog. Main difference from ancestor is that it calls
     * OnDateSetListener only when when pressing OK button, and skips event when closing with
     * BACK key or by tapping outside a dialog.
     */
    public class IBSDatePickerDialog extends DatePickerDialog {
    
        public IBSDatePickerDialog(final Context context, final OnDateSetListener callBack, final int year, final int monthOfYear, final int dayOfMonth) {
            super(context, callBack, year, monthOfYear, dayOfMonth);
        }
    
        public IBSDatePickerDialog(final Context context, final int theme, final OnDateSetListener callBack, final int year, final int monthOfYear, final int dayOfMonth) {
            super(context, theme, callBack, year, monthOfYear, dayOfMonth);
        }
    
        @Override
        public void onClick(final DialogInterface dialog, final int which) {
            // Prevent calling onDateSet handler when clicking to dialog buttons other, then "OK"
            if (which == DialogInterface.BUTTON_POSITIVE)
                super.onClick(dialog, which);
        }
    
        @Override
        protected void onStop() {
            // prevent calling onDateSet handler when stopping dialog for whatever reason (because this includes
            // closing by BACK button or by tapping outside dialog, this is exactly what we try to avoid)
    
            //super.onStop();
        }
    }
    

    Using dialog example (free bonus: adding Cancel button to dialog for even better usability):

    public static class datePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
    
        @Override
        public Dialog onCreateDialog(final Bundle savedInstanceState) {
    
            Calendar cal = Calendar.getInstance();
            IBSDatePickerDialog dlg = new IBSDatePickerDialog(myActivity, this, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));
    
            // Add Cancel button into dialog
            dlg.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", (OnClickListener) null);
    
            return dlg;
        }
    
        @Override
        public void onDateSet(final DatePicker view, final int year, final int month, final int day) {
            // TODO: do whatever you want with date selected
        }
    }
    
    public void showDatePickerDialog() {
        final datePickerFragment f = new datePickerFragment();
        f.show(getSupportFragmentManager(), "datePicker");
    }
    

提交回复
热议问题