Android: Create Calendars to select a specific date, or specific month in a year, or specific year

StackOverflow https://stackoverflow.com/questions/14513388

  •  17-01-2022
  •  | 
  •  

Question

I am looking to create 3 different Calendar views in my application, each triggered by a different button.

The first one is a standard calendar allowing you to pick a specific date. The second one is similar, except you just select the month as a whole rather than a day. The final one you just select the year as a whole.

I realize there is a CalendarView widget, but it is not available for API levels below 11.

I have seen a few custom ones around but they involve quite a number of classes, created by others and I don't really want to rely on them. I have also looked into DatePicker, because it doesn't necessarily need to look like a Calendar. If each date picker just had a spinner for the relevant field(s), that would work as well.

Was it helpful?

Solution 2

I managed to find a solution without the need to use other projects or starting from scratch. It is probably not the BEST solution, but it seems to work perfectly fine for me.

I used the DatePicker widget rather than a calendar as it is simpler and does exactly what I need. I essentially remove (View.GONE) the date picker until one of the buttons is selected (e.g. "select full date", "select month in year", "select year").

In the first case with the "select full date", I just set the date picker to VISIBLE. That is all that is required.

In the second case with "select month in a year", I set the date picker VISIBLE but I also call a method which using Reflection to hide the DAY part of the date picker.

The final case is like above, except I hide the DAY and MONTH part of the date picker.

In all the cases, a new button appears below the date picker "Set Date" or "Set Month" or "Set Year" (depending on which initial button was selected). Each of the buttons will extract the relevant field information from the date picker.

OTHER TIPS

To the best of my knowledge, you're gonna have to roll your own here. There's a little helper in android.util called MonthDisplayHelper which is useful for some of the basic calculations of displaying a 6 row calendar grid. Other than that, despite the relatively frequent use of calendars, there's no calendar widget or any built-in class like that really.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top