Stop closing DatePickerDialog when you click on the "Install" button

I implemented DatePickerDialog using the example below here .

In my implementation of DatePickerDialog.OnDateSetListener I added validation logic to verify that the selected date is in a 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 is that DatePickerDialog closes automatically when the user clicks the set button, and I want to leave DatePickerDialog open if the validation rule fails.

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

+4
source share
1 answer

From API 11, DatePicker can confirm your date.

Following the guide, you refer to when you redefine onCreateDialog, get a DatePicker, and set the minimum and maximum 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; } 

Thus, the user cannot select the wrong date, so there is no need to manually check the date.

For older versions, you can use a boolean to control when closure is allowed, and implement your own logic. Here I will try to illustrate where you need to extend the 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(); } 
+5
source

Source: https://habr.com/ru/post/1394035/


All Articles