简体   繁体   中英

Stopping the DatePickerDialog from closing when use clicks the Set button

I've implemented a DatePickerDialog using the example shown here .

In my implementation of the DatePickerDialog.OnDateSetListener I added validation logic to check that the selected date is within specific range.

private final DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {

    @Override
    public void onDateSet(DatePicker view, int y, int m,
            int d) {

            final Calendar calendar = Calendar.getInstance();
            calendar.set(y, m, d);
            Date date = calendar.getTime();

      if(!myValidationFunction(date)) {
        // date not within allowed range
        // cancel closing of dialog ?
      }
    }
};

The problem I have is that the DatePickerDialog is closed automaticlly when the user clicks the set button and I want to keep the DatePickerDialog open if the validate rule fails.

Does anyone know how to stop the DatePickerDialog from closing when the user clicks the Set button?

From API 11 the DatePicker can validate your date for you.

Following the guide you refer to , when overriding onCreateDialog, get DatePicker and set min and max date:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    // no changes from guide ...
    final DatePickerDialog dialog = new DatePickerDialog(getActivity(), this, year, month, day);
    dialog.getDatePicker().setMinDate(minDate);
    dialog.getDatePicker().setMaxDate(minDate);
    return dialog;
}

This way the user cannot pick a wrong date, thus no need to manually validate the date.

For older versions you can use a boolean for control when closing is allowed, and implement your own logic. Here I try to illustrate where you'll need to extend your code:

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        final DatePickerDialog dialog = new DatePickerDialog(getActivity(), this, year, month, day){

            @Override
            public void onBackPressed() {
                allowClose = true;
                super.onBackPressed();
            }

            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (which==DialogInterface.BUTTON_POSITIVE && validate()){
                    allowClose = true;
                }
                super.onClick(dialog, which);
            }

            @Override
            public void dismiss() {
                if (allowClose) {
                    super.dismiss();
                }
            }

        };

        return dialog;
    }

    private void onCancelBtnClick() {
        allowClose = true;
        dismiss();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM