Search code examples
androidandroid-dialogandroid-datepicker

Listener for DatePickerDialog +/- button


I'm currently using DatePickerDialog in my Android app.

As everyone, knows the dialog has three EditTexts: 1) for day 2) for month 3) for year. And there are + and - buttons for the three to move to front and back of the selected field. I need to know if there exists any listener for the "+" and "-" buttons in the dialog?

This is because, in my app, I don't want the user to select previous dates before the current date using the dialog. So if the "-" button is clicked, it should check whether the date in the dialog is less than the current date. So I need a listener for the "-" button of the dialog.

Also I'm developing this app for all platforms starting from Froyo to KitKat. I have heard that there is a setMinDate() for DatePicker. But it is available only from HoneyComb.


Solution

  • try overriding onDateChnaged() function, here is example:

    DatePickerDialog mDatePickerDialog = new DatePickerDialog(this, mDateSetListener,mYear, mMonth, mDay){
                    @Override
                    public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth){
                        // this function will call when user click on '+' or '-'. Apply validation here. you can call view.updateDate(mYear, mMonth, mDay); if u don't want to accept date that user trying to select by pressing +/- 
                        final Calendar c = Calendar.getInstance();
                        mYear = c.get(Calendar.YEAR);
                        mMonth = c.get(Calendar.MONTH);
                        mDay = c.get(Calendar.DAY_OF_MONTH);
                        /* this validation allow user to enter date less then current date */
                        if (year > mYear)
                            view.updateDate(mYear, mMonth, mDay);

                    if (monthOfYear > mMonth && year == mYear)
                        view.updateDate(mYear, mMonth, mDay);
    
                    if (dayOfMonth > mDay && year == mYear && monthOfYear == mMonth)
                        view.updateDate(mYear, mMonth, mDay);
                }
            };
    

    DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() { public void onDateSet(DatePicker view, int year, int monthOfYear,int dayOfMonth) { // Add your code here to handle selected date event by user

    } };