Create your own custom Calendar View
For the last week, i spend most of my days trying to find a quick and easy library/packages to display a calendar view for MeetU schedules. Turns out most of it have a limited UI component, property and behaviors :( Here is my journey creating MeetU’s very own CalendarView for Android.
Custom Component Layout
First, We’ll start with how the component look. We will create the calendar displaying the dates in grid, with the current dates in the top with “previous month” and “next month” buttons.
We will create the layout first within calendar_layout.xml
. This layout can be seen as 2 layouts, the top toolbar and the date grid.
The Class Component Itself
The layout will encapsulated in a UI component which provides modularity and prevents code repetition. We’ll define the component as a subclass of LinearLayout
in CalendarView.java
and firstly will bind all of the components used in the layout with the class’ instance variables.
Component’s Business Logic
Our component needs a business logic for it to behave as a calendar, here’s how we gonna break the logic down :
- The calendar view is seven days wide, all the months will start somewhere in the first row of the grid.
- We need to figure out what position the month starts at, then fill all of the previous positions with dates of the previous months.
- Then we filled the days in the current month.
- After filling all of the current month days, we will fill the rest of it with the next month’s dates.
Using Android’s build-in date functionality, and Java’s Calendar
class, we can implement this logic in our updateCalendar()
function:
Customize and Styling the dates
Since GridView
is the one responsible for displaying the individual dates in the calendar, a neat trick to style and customize the dates is by using an Adapter
provided by the GridView, since adapter
is responsible for inflating the views in the grid cells.
For this example, we will have these requirements:
- Present day should be highlighted
- Days outside the current month should be grayed out
We can implement these requirements by making an CalendarAdapter
that extends the ArrayAdapter<E>
and override the getView()
function :
Put all the pieces altogether to an activity, a layout and build it, and we get the following result :
That’s it ! With a little more touch up to the styling, we’re finally done with our own custom calendar view. Although it’s still a work in progress, creating this custom calendar was such a satisfying feeling at the end :)
To conclude..
The android UI models and components, although limited to its behaviour and UI, provides an customizable implementation through Inheritance and Adapter Pattern, and this is an example of customizing the CalendarView for MeetU.