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.
How to show the Calender of only one year from current date in Android?
-
04-06-2022 - |
Question
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
OTHER TIPS
try creating a calender as below instead of calling Calender.getInstance();
Calendar minCal = new GregorianCalendar(2013, Calendar.JANUARY, 1);
Use setMinDate()
and setMaxDate()
on the DatePicker
. You can access it from your DatePickerDialog
with getDatePicker()
(requires API level 11).
http://developer.android.com/reference/android/widget/DatePicker.html
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow