26

i am using following example of date picker

http://developer.android.com/guide/tutorials/views/hello-datepicker.html

now i want to perform some functionality on clicking date picker cancel button but dont see cancel event inside datepickerdialog

can any one guide me how to achieve this.

any help would be appreciated.

angryITguy
  • 9,332
  • 8
  • 54
  • 82
UMAR-MOBITSOLUTIONS
  • 77,236
  • 95
  • 209
  • 278

13 Answers13

80

Here's how I did it:

  DatePickerDialog dialog = new DatePickerDialog(this,
              mDateSetListener,
              year, month, day);

  dialog.setButton(DialogInterface.BUTTON_NEGATIVE, getString(R.string.cancel), new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
       if (which == DialogInterface.BUTTON_NEGATIVE) {
          // Do Stuff
       }
    }
  });
esilver
  • 27,713
  • 23
  • 122
  • 168
8

If you want to perform a different action depending on whether the user selected a date or not you can use an onDismiss handler. Be sure to set a Boolean (e.g., "isDataSet") to indicate whether the user selected a date or not. Here's an example:

// Date Picker Dialog
   public void showDatePickerDialog(View view) {
   int year, month, day;
   isDataSet = false;  // this is used by the onDismiss handler

// Set initial time period in DatePicker to current month
   calendarCurrent = Calendar.getInstance(); 
   month = calendarCurrent.get(Calendar.MONTH);
   day =   calendarCurrent.get(Calendar.DAY_OF_MONTH);
   year =  calendarCurrent.get(Calendar.YEAR);

   DatePickerDialog datePickerDialog = new DatePickerDialog(YourActivity.this, dateSetListener, year, month, day );
   datePickerDialog.setOnDismissListener(mOnDismissListener);
   datePickerDialog.show();
   datePickerDialog_visible=true;  //indicate dialog is up
 } // [END showDatePickerDialog] 

//onDismiss handler
private DialogInterface.OnDismissListener mOnDismissListener =
        new DialogInterface.OnDismissListener() {
            public void onDismiss(DialogInterface dialog) {
                datePickerDialog_visible=false;  //indicate dialog is cancelled/gone
                if (isDataSet) {  // [IF date was picked
                    //do something, date now selected
                } else {
                    //do someething else, dialog cancelled or exited
                }   
            }
        };
PeteH
  • 1,870
  • 25
  • 23
6

Since DatePickerDialog is a Dialog, it supports the following:

setOnCancelListener(OnCancelListener listener)
setOnDismissListener(OnDismissListener listener)

Using both listeners, you can identify all dismissals of the date picker dialog. The first would answer the question, the latter is for completion.

Eran Boudjnah
  • 1,228
  • 20
  • 22
6
DatePickerDialog dialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {


            }
        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));

        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialogInterface) {

            }
        });
        dialog.show();
Karan Datwani
  • 532
  • 6
  • 6
1

DatePickerDialog now exposes a onCancel listener.

DatePickerDialog datePickerDialog = DatePickerDialog.newInstance(new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePickerDialog datePickerDialog, int year, int month, int day) {
            // Do whatever you want when the date is selected.
            editText.setText(String.format("%04d-%02d-%02d", year, month+1, day));
        }
    }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH));

    datePickerDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) {

        }
    });
Harsh
  • 460
  • 5
  • 9
1

I added some additional code to @PeteH great answer (which provides for reacting to user pressing date or cancelling).

private void showDatePickerDialog() {
    final int[] year = new int[1];
    final int[] month = new int[1];
    final int[] day = new int[1];
    isDataSet = false;  // this is used by the onDismiss handler

    // Set initial time period in DatePicker to current month
    Calendar calendarCurrent = Calendar.getInstance();
    month[0] = calendarCurrent.get(Calendar.MONTH);
    day[0] =   calendarCurrent.get(Calendar.DAY_OF_MONTH);
    year[0] =  calendarCurrent.get(Calendar.YEAR);

    DatePickerDialog datePickerDialog = new DatePickerDialog(
            MyActivity,
            new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker datePicker, int y, int m, int d) {
            isDataSet =true;
            //user confirms date
            year[0] =y;
            month[0] = m;
            day[0] =d;

            //do something with date selected

        }
    },
            year[0],
            month[0],
            day[0]
    );
    datePickerDialog.setOnDismissListener(mOnDismissListener);
    datePickerDialog.show();
}
private DialogInterface.OnDismissListener mOnDismissListener =new DialogInterface.OnDismissListener() {
    public void onDismiss(DialogInterface dialog) {
        if (!isDataSet){

            //do something if user cancels

    }
};
seekingStillness
  • 4,833
  • 5
  • 38
  • 68
1

For kotlin, on dismiss and on cancel click listener ->

    datePickerDialog.setOnDismissListener {
        //on dismiss
    }

    datePickerDialog.setButton(
        DialogInterface.BUTTON_NEGATIVE, "Cancel"
    ) { _, which ->
        if (which == DialogInterface.BUTTON_NEGATIVE) {
            //on cancel click
        }
    }
Kunal Kalwar
  • 685
  • 6
  • 20
0

The following code helped me solve an issue with the Cancel button not closing out the Date picker window. Thanks to eSilver for the solution.

dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() 
{
    public void onClick(DialogInterface dialog, int which) {
        if (which == DialogInterface.BUTTON_NEGATIVE) {
            datePickerPlugin.success(new PluginResult(PluginResult.Status.OK, ""), callBackId);
            dateDialog.hide();
        }
    }
});
Vijay
  • 1
  • Now can you please tell me how to know inside my onclick button what date user has been set ?? i mean inside above function i want yy, mm, dd coz i will set them again in my edittext ?? – Sudhanshu Gaur Jun 01 '16 at 16:04
0

Sorry for popping up ancient question, but I faced similar problem and wrote simple successor of standard DatePickerDialog with proper behavior. See it in this topic. I hope this helps.

Community
  • 1
  • 1
Denys Avilov
  • 427
  • 1
  • 4
  • 8
0

In this part of the code:

 private DatePickerDialog.OnDateSetListener mDateSetListener =
            new DatePickerDialog.OnDateSetListener() {

                public void onDateSet(DatePicker view, int year, 
                                      int monthOfYear, int dayOfMonth) {
                    mYear = year;
                    mMonth = monthOfYear;
                    mDay = dayOfMonth;
                    updateDisplay();
                }
            };

you have to implement also onClick():

public void  onClick  (DialogInterface  dialog, int which) {
   if (which == Button.NEGATIVE) {
      //Cancel
   }
}

API for Button.NEGATIVE

0
public void showDatePicker() {

        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        DatePickerDialog datePicker = new DatePickerDialog(getActivity(), (view, year1, month1, day1) -> {
            Calendar c1 = Calendar.getInstance();
            c1.set(year1, month1, day1);
            Date date = c1.getTime();
            SimpleDateFormat formatter = new SimpleDateFormat("dd MMMM yyyy");
            String d = formatter.format(date);
//            btnDatePicker.setText(d);
//            selectedDate = d;
        }, year, month, day) {
            @Override
            public void onClick(@NonNull DialogInterface dialog, int which) {
                super.onClick(dialog, which);
                if (which == DialogInterface.BUTTON_POSITIVE) {
                } else if (which == DialogInterface.BUTTON_POSITIVE) {

                }
            }
        };

        datePicker.getDatePicker().setMinDate(System.currentTimeMillis());
        datePicker.show();
    }
aanshu
  • 1,602
  • 12
  • 13
0

Simply, if you are using or extending AppCompatDialogFragment() just override the

override fun onCancel(dialog: DialogInterface) {
    super.onCancel(dialog)
    // write your own code 
}

That is it :)

Mina Samir
  • 1,527
  • 14
  • 15
-3

Try this:

if (resultCode == RESULT_CANCELED) {
    Toast toast = Toast.makeText(this,"Datepicker Canceled", 10000);
    toast.show();
    return;
}
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Srikanth Naidu
  • 787
  • 5
  • 16
  • 28
  • 1
    in which event should i use it? – UMAR-MOBITSOLUTIONS May 31 '10 at 05:03
  • you will be firing an Datepicker activity on Click, so on the public void onActivityResult() event u can call this code public void onActivityResult() { if (resultCode == RESULT_CANCELED) { Toast toast = Toast.makeText(this,"Datepicker Cancled", 10000); toast.show(); return; } } – Srikanth Naidu May 31 '10 at 09:00
  • No idea what this is about - there's not a DatePickerActivity, it's a dialog, so it remains within the activity. – esilver Feb 12 '11 at 23:26