Search code examples
javaandroidandroid-datepickerandroid-dateandroid-dateutils

How to show the Calender of only one year from current date in Android?


I want that the calender show user only one year date and rest will be disabled for the past it is working fine .But now i want to make so that the user can select only one year calender from current date.here is my code .Please suggest me the changes.

textView1.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    showDialog(DATE_DIALOG_ID);

                }
            });


    protected Dialog onCreateDialog(int id) {
        final Calendar now = Calendar.getInstance();

        switch (id) {
        case DATE_DIALOG_ID:
            // set date picker as current date
            DatePickerDialog _date =   new DatePickerDialog(this, date,myCalendar
                    .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                    myCalendar.get(Calendar.DAY_OF_MONTH)){
                @Override
                public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth)
                {   
                    if (year < now.get(Calendar.YEAR))

                        view.updateDate(myCalendar
                                .get(Calendar.YEAR), myCalendar
                                .get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH));

                    if (monthOfYear < now.get(Calendar.MONTH) && year == now.get(Calendar.YEAR))
                        view.updateDate(myCalendar
                                .get(Calendar.YEAR), myCalendar
                                .get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH));

                    if (dayOfMonth < now.get(Calendar.DAY_OF_MONTH) && year == now.get(Calendar.YEAR) && 
                            monthOfYear == now.get(Calendar.MONTH))
                        view.updateDate(myCalendar
                                .get(Calendar.YEAR), myCalendar
                                .get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH));
                        }
            };
            return _date;
        }
        return null;
    }

Solution

  • Get the current date. then increase the year value by one. then use setMaxDate function as How set maximum date in datepicker dialog in android? question shows.