Search code examples
androidandroid-datepicker

Show 1980 as initial Year in Date Picker


How to show 1980 as initial Year in DatePicker dialog, still i am getting initial date as current date

see my code below, and let me know where i have to do changes in my code

     @Override
        protected Dialog onCreateDialog(int id) {
            switch (id) {
            case DIALOG_DATE:
                return new DatePickerDialog(this, new OnDateSetListener() {

                    @Override
                    public void onDateSet(DatePicker view, int year,
                            int monthOfYear, int dayOfMonth) {
                        dateTime.set(year, monthOfYear, dayOfMonth);
                        editDate.setText(dateFormatter
                                .format(dateTime.getTime()));
                    }
                }, dateTime.get(Calendar.YEAR),
                   dateTime.get(Calendar.MONTH),
                   dateTime.get(Calendar.DAY_OF_MONTH));
            }
            return null;

Solution

  • That is because the last 3 parameters on the DatePickerDialog constructor are the date to be shown initially in the DatePicker. You are setting the dateTime variable to the current day with

    private Calendar dateTime = Calendar.getInstance();
    

    So you must set your dateTime variable to the correct date you want to be shown on the first run. In your OnCreate() method do this

    dateTime.set(1980, Calendar.JANUARY , 1);
    

    Now your DatePicker should show the correct value on the first run and since you set the dateTime variable in the callback it should set the correct previous value if the user opens up the dialog again.