Calendar view android studio

Calendar view android studio

Сегодня мы разберем такой простой и всем известный элемент пользовательского интерфейса Android платформы, как календарь. Чтобы интегрировать стандартный календарь в свое приложение, разработчики используют элемент под названием CalendarView, который появился аж с 3-й версии операционной системы. С помощью различных атрибутов, можно покрутить и настроить вид календаря под свой вкус, хотя настроек не так уж много. Например, присутствуют такие атрибуты:

android:firstDayOfWeek — выставляем первый день недели;

android:minDate — минимальная дата, которую будет показывать календарь, которая задается в формате mm/dd/yyyy (месяц, день, год);

android:selectedWeekBackgroundColor — фоновый цвет для выбранной недели;

android:showWeekNumber — здесь мы можем выставить, показывать номер недели или нет;

android:weekNumberColor — цвет для номер недели;

android:weekSeparatorLineColor — цвет линии, разделяющей недели и тп.

Мы не будем слишком кастомизировать свой календарь, а точнее вообще не будем, мы просто сделаем приложение, отображающее календарь и настроим ему слушателя изменений выбранной даты. Для каждого нажатия по любому дню в календаре мы, используя метод onSelectedDayChange (), будем показывать Toast сообщение с информацией о выбранной дате.

Создаем новый проект, выбираем Blank Activityи минимальную версию Android 4.0+.

В файле activity_main.xml создаем календарь:

Теперь переходим к файлу MainActivity.java. Здесь мы объявляем CalendarView, ссылаемся на наш календарь в файле интерфейса, задаем ему слушателя смены даты setOnDateChangeListener, а также используя метод onSelectedDayChange, при смене даты выводим Toast сообщение с выбранной датой:

Вот и все, на этом знакомство с системным Android календаря заканчивается, запускаем приложение и смотрим на результат:

Работает нормально, правда почему то в Google считают, что январь это 0-й месяц, поэтому май показывает как 4. Чтобы исправить, можно в настройках Toast сообщения, добавить к значению месяца единицу.

Источник

CalendarView

Компонент CalendarView находится в разделе Widgets и выводит на экран календарь.

Описание всех атрибутов можно взять из документации.

В данном случае я выбрал цвет для выбранной недели (красный), цвет для номера недели (синий) и цвет для разделителей (зелёный). Спустя несколько лет обнаружил, что данные атрибуты теперь считаются устаревшими и игнорируются.

Выбранную дату можно отслеживать через метод setOnDateChangeListener():

Получить выбранную дату

В предыдущем примере мы получали выбранную дату через слушатель. Получить выбранную дату по щелчку кнопки по идее можно через метод getDate(). По крайней мере в документации говорится, что возвращается выбранная дата, но в реальности возвращается сегодняшняя дата. Оставил пример для демонстрации взаимодействия между CalendarView и объектом Calendar.

Добавим на экран активности кнопки и напишем код для её щелчка.

Программно установить дату в CalendarView

Сделаем обратную задачу — мы получили дату в виде объекта Calendar и хотим установить её в CalendarView. Не забывайте, что отсчёт месяцев идёт с 0.

Вместо вызова свойства calendarView.date можно вызвать метод setDate(), который имеет перегруженную версию с тремя параметрами.

Установить минимальную и максимальную даты

Компонент позволяет установить минимальную и максимальную даты через атрибуты minDate и maxDate, все остальные даты вне заданного промежутка будут недоступны.

Также можно установить эти даты программно через calendarView.minDate и calendarView.maxDate.

Дополнительное чтение

prolificinteractive/material-calendarview — по уверению автора, лучший вариант календаря, чем системный.

vikramkakkar/SublimePicker позволяет выбрать дату, время и повторяющие интервалы.

Источник

Calendar view android studio

Material-Calendar-View is a simple and customizable calendar widget for Android based on Material Design. The widget has two funcionalities: a date picker to select dates (available as an XML widget and a dialog) and a classic calendar. The date picker can work either as a single day picker, many days picker or range picker.

We described a simple usage of the component in this article.

  • Material Design
  • Single date picker
  • Many dates picker
  • Range picker
  • Events icons
  • Fully colors customization
  • Customized font

Make sure you are using the newest com.android.support:appcompat-v7.

Make sure you are using Java 8 in your project. If not, add below code to build.gradle file:

Make sure you have defined the jcenter() repository in project’s build.gradle file:

Add the dependency to module’s build.gradle file:

or if you want to use very early version with CalendarDay support:

To your XML layout file add:

Adding events with icons:

How to create icons?

Drawable with text:

You can use our utils method to create Drawable with text

Take a look at sample_three_icons.xml and adjust it to your project

Getting a selected days in the picker mode:

If you want to get all selected days, especially if you use multi date or range picker you should use the following code:

. or if you want to get the first selected day, for example in case of using single date picker, you can use:

Setting a current date:

Setting minumum and maximum dates:

Setting disabled dates:

Setting highlighted days:

Setting selected dates:

. or if you want to remove selected dates:

  • Don’t pass more than one calendar object to method above if your calendar type is CalendarView.ONE_DAY_PICKER .
  • If your calendar type is CalendarView.RANGE_PICKER you have to pass full dates range. To get it you can use our utils method CalendarUtils.getDatesRange(Calendar firstDay, Calendar lastDay) .

Previous and forward page change listeners:

If you want to use calendar in the picker mode, you have to use the following tags:

  • app:type=»one_day_picker»
  • app:type=»many_days_picker»
  • app:type=»range_picker»

If you want to display event icons in the picker mode, add:

  • Header color: app:headerColor=»[color]»
  • Header label color: app:headerLabelColor=»[color]»
  • Previous button image resource: app:previousButtonSrc=»[drawable]»
  • Forward button image resource: app:forwardButtonSrc=»[drawable]»
  • Abbreviations bar color: app:abbreviationsBarColor=»[color]»
  • Abbreviations labels color: app:abbreviationsLabelsColor=»[color]»
  • Calendar pages color: app:pagesColor=»[color]»
  • Selection color in picker mode: app:selectionColor=»[color]»
  • Selection label color in picker mode: app:selectionLabelColor=»[color]»
  • Days labels color: app:daysLabelsColor=»[color]»
  • Color of visible days labels from previous and next month page: app:anotherMonthsDaysLabelsColor=»[color]»
  • Disabled days labels color: app:disabledDaysLabelsColor=»[color]»
  • Highlighted days labels color: app:highlightedDaysLabelsColor=»[color]»
  • Today label color: app:todayLabelColor=»[color]»

Custom view for days cells:

To use custom view for calendar cells create XML file (like in example below) and set it using setCalendarDayLayout(@LayoutRes layout: Int) method. XML file must contain TextView with id dayLabel and can contain ImageView with id dayIcon . Do not set colors or textStyle here, it will be overwritten.

Customization of specific cells:

If you want to customize specyfic cells create list of CalendarDay objects and pass it by setCalendarDays() method like in example below:

In the future CalendarDay will replace EventDay .

  • To create font directory Right-click the res folder and go to New > Android resource directory. — The New Resource Directory window appears.
  • In the Resource type list, select font, and then click OK.
  • Note: The name of the resource directory must be font.
  • Add your ttf or otf fonts in font folder. As an example we ad sample_font.ttf and sample_font_bold.ttf
  • On a DatePickerBuilder apply .typefaceSrc(R.font.sample_font) for setting sample_font to callendar and its abbreviations.
  • Optionally apply .todayTypefaceSrc(R.font.sample_font_bold) to differentiate today date font form the rest of dates in calendar view

Disable month swipe:

If you want to disable the swipe gesture to change the month, you have to use the following tag:

First day of a week:

If you want to change default first day of week:

By default the first day is monday or sunday depending on user location.

Источник

Android Calendar View

Android Tutorial

In this tutorial, we’ll be discussing the Calendar Widget using the CalendarView class in our Android Application.

Android Calendar View

As the name suggests, a Calendar View is used to display and select dates of the Calendar.

To add a CalendarView in the XML Layout do the following:

This is how it looks in the Layout Design editor :

When you’ll run the above application on your device, it’ll show the current date. By default, the Calendar shows the Jan 1, 1970, date.

android:maxDate and android:minDate are used to set a custom range on the calendar. The dates specified are of the format MM/dd/yyyy.

To do the same in Java we use setMaxDate() and setMinDate() methods passing the long instance. The getters methods are available for the same.

To set the current date we do setDate(long date) on the CalendarView instance.

The setDate method has another form: setDate(long date, boolean animate, boolean center) .
By default the second and third parameters are true. When you select a new date it animates to it.

To change the date and week text style we use the attributes:
android:dateTextAppearance and android:weekTextAppearance or their equivalent setters in Java.

The CalendarView consists of the following listener:

This gets triggered whenever the date is changed by the user.

In the following section, we’ll create an android application with a custom theme and add a custom range on the CalendarView along with showing the difference between animation and non-animation date changes.

Project Structure

In the styles.xml file add the following three styles:

android:textColorPrimary by default is white. This color is set on the month date and the left and right indicators.

The code for the activity_main.xml is given below:

We’ve added all the custom styles in the layout above.

The three Buttons are chained in the Constraint Layout.

The code for the MainActivity.java is given below:

calendar.getActualMaximum(Calendar.DATE) gets the end of the month for the current date.
We’ve used SimpleDateFormat to convert the dates into a custom format.

The output of the application in action is given below:

In the first case, we animate to another date with animation. In the last case, the custom range shows only the July Month. The indicators are disabled.

This brings an end to this tutorial. You can download the project from the link below:

Источник

Calendar view android studio

A highly customizable calendar library for Android, powered by RecyclerView.

With this library, your calendar will look however you want it to.

  • Single or range selection — The library provides the calendar logic which enables you to implement the view whichever way you like.
  • Week or month mode — show 1 row of weekdays, or any number of rows from 1 to 6.
  • Disable desired dates — Prevent selection of some dates by disabling them.
  • Boundary dates — limit the calendar date range.
  • Custom date view — make your day cells look however you want, with any functionality you want.
  • Custom calendar view — make your calendar look however you want, with whatever functionality you want.
  • Custom first day of the week — Use any day as the first day of the week.
  • Horizontal or vertical scrolling mode.
  • Month headers and footers — Add headers/footers of any kind on each month.
  • Easily scroll to any date or month view using the date.
  • Use all RecyclerView customisations(decorators etc) since CalendarView extends from RecyclerView.
  • Design your calendar however you want. The library provides the logic, you provide the views.

It’s very important to check out the sample app. Most techniques that you would want to implement are already implemented in the examples.

Download the sample app here

View the sample app’s source code here

The library uses java.time classes via Java 8+ API desugaring for backward compatibility since these classes were added in Java 8.

To setup your project for desugaring, you need to first ensure that you are using Android Gradle plugin 4.0.0 or higher.

Then include the following in your app’s build.gradle file:

You can find the latest version of desugar_jdk_libs here.

Add the JitPack repository to your project level build.gradle :

Add CalendarView to your app build.gradle :

You can find the latest version of CalendarView on the JitPack badge above the preview images.

Note: If you’re upgrading from version 0.3.x to 0.4.x or 1.x.x, see the migration guide.

Add CalendarView to your XML like any other view.

See all available attributes.

Create your day view resource in res/layout/calendar_day_layout.xml .

Create your view container which acts as a view holder for each date cell. The view passed in here is the inflated day view resource which you provided.

Provide a DayBinder for the CalendarView using your DayViewContainer type.

Setup the desired dates in your Fragment or Activity:

And that’s all you need for a simple usage!

To add a header or footer to each month, the procedure is the same. Just provide your monthHeaderResource or monthFooterResource attribute, then set the monthHeaderBinder or monthFooterBinder property of the CalendarView. For more complex usages, please see the sample project.

In the example above, we get the first day of the week from the current locale, however, we can use a specific day regardless of locale by passing in the value DayOfWeek.SUNDAY , DayOfWeek.MONDAY etc

XML (All prefixed cv_ for clarity)

dayViewResource: The xml resource that is inflated and used as the day cell view. This must be provided.

monthHeaderResource: The xml resource that is inflated and used as a header for every month.

monthFooterResource: The xml resource that is inflated and used as a footer for every month.

orientation: The calendar orientation, can be horizontal or vertical . Default is vertical .

scrollMode: The scrolling behavior of the calendar. Can be paged or continuous . If paged , the calendar will snap to the nearest month after a scroll or swipe action. Default value is continuous .

maxRowCount: The maximum number of rows(1 to 6) to show on each month. If a month has a total of 6 rows and maxRowCount is set to 4, there will be two appearances of that month on the calendar, the first one will show 4 rows and the second one will show the remaining 2 rows. To show a week mode calendar, set this value to 1, you may also want to set hasBoundaries to false so dates can overflow into the previous/next month for a better experience.

hasBoundaries: Determines if dates of a month should stay in its section or can flow into another month’s section. If true , a section can only contain dates belonging to that month, its inDates and outDates. if false , the dates are added continuously, irrespective of month sections.

When this property is false , a few things behave slightly differently:

  • If inDateStyle is either allMonths or firstMonth , only the first index will contain inDates.
  • If outDateStyle is either endOfRow or endOfGrid , only the last index will contain outDates.
  • If outDateStyle is endOfGrid , outDates are generated for the last index until it satisfies the maxRowCount requirement.

inDateStyle: This Determines how inDates are generated for each month on the calendar. If set to allMonths , the calendar will generate inDates for all months, if set to firstMonth inDates will be generated for the first month only and if set to none , inDates will not be generated, this means that there will be no offset on any month.

outDateStyle: This determines how outDates are generated for each month on the calendar. If endOfRow , the calendar will generate outDates until it reaches the first end of a row. This means that if a month has 6 rows, it will display 6 rows and if a month has 5 rows, it will display 5 rows. However, if this value is set to endOfGrid , the calendar will generate outDates until it reaches the end of a 6 x 7 grid. This means that all months will have 6 rows.

If you are wondering what outDates and inDates mean, let’s use the screenshot below as an example.

In the image, the dates within the green annotation are inDates , the ones within the red annotation are outDates while those without annotation are monthDates . You can check for this when binding your calendar. To achieve the exact effect on the image, we do this:

inDates have their owner property set to DayOwner.PREVIOUS_MONTH

outDates have their owner property set to DayOwner.NEXT_MONTH

monthDates have their owner property set to DayOwner.THIS_MONTH as seen in the code snippet above.

All XML attributes are also available as properties of the CalendarView class via code. So in addition to those, we have:

monthScrollListener: Called when the calendar scrolls to a new month. Mostly beneficial if scrollMode is paged .

dayBinder: An instance of DayBinder for managing day cell views.

monthHeaderBinder: An instance of MonthHeaderFooterBinder for managing header views.

monthFooterBinder: An instance of MonthHeaderFooterBinder for managing footer views.

daySize: The size, in pixels for each day cell view.

Note that setting the daySize property to CalendarView.SIZE_SQUARE makes the day cells have equal width and height which is basically the width of the calendar divided by 7. SIZE_SQUARE is the default size value.

scrollToDate(date: LocalDate): Scroll to a specific date on the calendar. Use smoothScrollToDate() to get a smooth scrolling animation.

scrollToMonth(month: YearMonth): Scroll to a month on the calendar. Use smoothScrollToMonth() to get a smooth scrolling animation.

notifyDateChanged(date: LocalDate): Reload the view for the specified date.

notifyMonthChanged(month: YearMonth): Reload the header, body and footer views for the specified month.

notifyCalendarChanged(): Reload the entire calendar.

findFirstVisibleMonth() and findLastVisibleMonth(): Find the first and last visible months on the CalendarView respectively.

findFirstVisibleDay() and findLastVisibleDay(): Find the first and last visible days on the CalendarView respectively.

setupAsync(): Setup the CalendarView, asynchronously, useful if your startMonth and endMonth values are many years apart.

updateMonthRange(): Update the CalendarView’s startMonth and/or endMonth values after the initial setup. The currently visible month is preserved. Use updateMonthRangeAsync() to do this asynchronously.

updateMonthConfiguration(): Update inDateStyle , outDateStyle , maxRowCount and hasBoundaries properties without generating the underlying calendar data repeatedly. Prefer this if setting more than one of these properties at the same time. Use updateMonthConfigurationAsync() to do this asynchronously.

There’s no need to list all available methods or repeating the documentation here. Please see the CalendarView class for all properties and methods available with proper documentation.

You should set a click listener on the view which is provided to the view container.

XML file for the date cell calendar_day_layout.xml :

Of course, you need to set the file as cv_dayViewResource on the CalendarView:

Click listener implementation in your Fragment or Activity:

The library has no inbuilt concept of selected/unselected dates, this gives you the freedom to choose how best you would like to implement this use case.

Implementing date selection is as simple as showing a background on a specific date in the date binder, remember that since CalendarView is a RecyclerView, you need to undo any special effects on dates where it is not needed.

For this example, I want only the last clicked date to be selected on the calendar.

Firstly, let’s keep a reference to the selected date:

Next, using the click logic already shown in the date click section above, we update this field whenever a date is clicked and show the selection background on the clicked date.

Lastly, we implement the dayBinder to reflect the selection accordingly:

For more complex selection logic like range selection, please see the sample project. It’s quite simple, the magic is all in your binding logic!

As expected, the library does not provide this logic internally so you have complete flexibility.

To disable dates, you can simply set the texts on those dates to look «disabled» and ignore clicks on those dates. For example, if we want to show in and out dates but «disable» them so that they cannot be selected, we can just set the alpha property for those dates in the dayBinder to give the effect of being disabled.

Continuing with the example in the date selection section, we already ignore clicks for in and out dates using this logic:

Then in the dayBinder , we check the day owner again and bind accordingly:

And that’s all you need to do. Of course you can go wild and do a whole lot more, see the sample project for some complex implementations.

Adding month headers and footers

This is quite simple, just provide the needed values for cv_monthHeaderResource or cv_monthFooterResource in XML or programmatically. In the example shown below, we add a header which simply shows the month name above each month:

Create the header view in res/layout/calendar_month_header_layout.xml :

Set the view as the month header resource:

Finally, provide a month header binder in code:

The same logic applies if you need to add a footer.

First day of the week

Here’s a method which generates the weekdays from the user’s current Locale.

With the method above, you can set up the calendar so the first day of the week is what the user would expect. This could be Sunday, Monday or whatever the Locale returns:

Of course, this could be simplified as:

However, you would typically use the daysOfWeek array values to set up the weekday texts in your month header view, this way it matches what is shown on the calendarView.

To use Sunday as the first day of the week, regardless of the user’s Locale, use the below logic instead:

Week view and Month view

This library has no concept of week/month view. You’ll need to configure the calendar to mimic this behavior by changing its state between a 6 or 1 row calendar, depending on your needs. This feature can be seen in Example 1 in the sample app. In summary, here’s what you need:

With the configuration above, you get the result below:

If you wish to animate height changes on the CalendarView when switching between week and month modes, please see Example 1 in the sample app where we use a ValueAnimator , of course you can use whichever animation logic you prefer.

You can also set hasBoundaries to true for a week mode calendar. This helps the library make very few optimizations, however, you should also change scrollMode to ScrollMode.CONTINUOUS as pagination behavior may not be as expected due to boundary limitations. See Example 7 in the sample app for a week mode calendar with this configuration, a screenshot is shown below:

Remember that all the screenshots above are just examples of what you can achieve with this library and you can absolutely build your calendar to look however you want.

Made a cool calendar with this library? Share an image here.

Q: How do I use this library in a Java project?

A: It works out of the box, however, the MonthScrollListener is not an interface but a Kotlin function. To set the MonthScrollListener in a Java project see this.

Q: How do I disable user scrolling on the calendar so I can only scroll programmatically?

A: See this.

Q: Why am I getting the same YearMonth value in the CalendarMonth passed into the MonthScrollListener ?

A: This is because you have set app:cv_hasBoundaries to false in XML or have called calendarView.hasBoundaries = false in code. When this is set, the underlying YearMonth is undefined on all indices as each index could have multiple months depending on your maxRowCount value. If you need the month value with the hasBoundaries = false setting, you can get it from any of the CalendarDay values in the CalendarMonth class. You can always check if the first and last dates are from different months and act accordingly.

If you’re upgrading from version 0.3.x to 0.4.x or 1.x.x, the main change is that CalendarView moved from using ThreeTenABP to Java 8 API desugaring for dates. After following the new setup instructions, the next thing you need to do is change your imports for date/time related classes from org.threeten.bp.* to java.time.* .

You also need to remove the line AndroidThreeTen.init(this) from the onCreate() method of your application class as it’s no longer needed.

Found a bug? feel free to fix it and send a pull request or open an issue.

CalendarView was inspired by the iOS library JTAppleCalendar. I used JTAppleCalendar in an iOS project but couldn’t find anything as customizable on Android so I built this. You’ll find some similar terms like InDateStyle , OutDateStyle , DayOwner etc.

CalendarView is distributed under the MIT license. See LICENSE for details.

About

A highly customizable calendar library for Android, powered by RecyclerView.

Источник

Читайте также:  Vogue collection для андроид
Оцените статью