Android calendarview get selected date

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 позволяет выбрать дату, время и повторяющие интервалы.

Источник

Как получить дату с calendarview?

Как получить дату с calendarview?
Всех с новым годом поздравляю и + я новичок по android studio, так что не кидайтесь тапками. Пишу.

В SQL запросе получить дату начала и дату конца следующего месяца
В SQL запросе необходимо использовать дату начала следующего месяца, и дату конца следующего.

Получить текущую дату без времени и вычесть другую дату
Ребята нужна помощь знатоков. Беру с сайта дату List datew =.

Дата: Получить текущую дату и дату +7 дней.
В общем проблема такая. Через кнопку у меня должно появляться текущее дата и рядом дата +7.

Ну слушатель и слушатель Вы же обрабатываете нажатие на кнопку?
Можно конечно и так.
Тогда меняем:

Объясните, пожалуйста, зачем вам использовать коллбэк (слушатель) ?
Вы его можете полностью стереть, ведь получить дату надо по нажатию на кнопку, так?

Вот метод полностью

выбираешь дату на календаре (это слушатель) и нажимаешь на кнопку потом она загружает все в базу данных

Добавлено через 9 минут
Надо что бы пользователь приложение выбирал дату сам, а не по умолчанию вот для этого слушатель

Есть две строки textview(String name, String lastname) calendarview(String date) и кнопка button(addpost). При нажатие на кнопку он собирает все в class Post и заполняет конструктор Post post = new Post(String name, String lastname, String date) и отправляет

Источник

Tutorialwing

Hello Readers! In this post, we are going to learn about how to use android calendarView widget in any android application. We will also go through different attributes of calendarView widget that can be used to customise it.

Output

Tutorialwing Android calendarView Output

Tutorialwing Android calendarView Output

Getting Started

CalendarView widget can be defined as below –

CalendarView is a widget that are used to display and select dates. However, you can configure range of dates to be shown in the calendar.

Attributes of Android CalendarView Widget

Some of the popular attributes of android CalendarView widget are –

Sr. XML Attributes Description
1 android:dateTextAppearance The text appearance for the day numbers in the calendar grid
2 android:firstDayOfWeek Defines first day of the calendar
3 android:maxDate Defines maximal date shown in calendar view in mm/dd/yyyy format
4 android:minDate Defines minimal date shown in calendar view in mm/dd/yyyy format

Some of the popular attributes of android calendarView widget inherited from FrameLayout are –

Sr. XML Attributes Description
1 android:foregroundGravity Defines the gravity to apply to the foreground drawable
2 android:measureAllChildren Defines whether to measure all children or only those in VISIBLE or INVISIBLE state when measuring

Some of the popular attributes of android calendarView inherited from viewGroup are –

Sr. XML Attributes Description
1 android:animateLayoutChanges Specifies whether to run layout transition when there is any change in layout
2 android:animationCache Specifies whether to create drawing cache for children by layout animation
3 android:clipToPadding Defines whether the ViewGroup will clip its children and resize (but not clip) any EdgeEffect to its padding, if padding is not zero
4 android:layoutAnimation Specifies the layout animation to be used when the viewGroup is laid out for the first time
5 android:layoutMode Defines the layout mode of the viewGroup

Some of the popular attributes of android calendarView inherited from View are –

Sr. XML Attributes Description
1 android:alpha Sets alpha to the view
2 android:background Sets drawable to the background
3 android:backgroundTint Sets tint to apply to the background
4 android:clickable Specifies whether the view is clickable or not
5 android:elevation Sets elevation of the view
6 android:focusable Specifies whether this view can take focus or not
7 android:id Specifies id of the view
8 android:visibility Specifies the visibility(VISIBLE, INVISIBLE, GONE) of the view
Читайте также:  Start setting для андроид

Example of Android CalendarView Widget

At first, we will create android application. Then, we will use calendarView widget in this application.

1. Creating New Project

Follow steps below to create new project. Please ignore the steps if you have already created a new application.

Step Description
1. Open Android Studio.
2. Go to File => New => New Project. Write application name as CalendarView. Then, click next button.
3. Select minimum SDK you need. However, we have selected 17 as minimum SDK. Then, click next button
4. Then, select Empty Activity => click next => click finish.
5. If you have followed above process correctly, you will get a newly created project successfully. However, you can also visit post to create a new project to know steps in detail.

Now, we will modify xml and java file to use calendarView widget in the application.

2. Modify Values folder

No values folders have been modified. So, we are not going to mention them here.

3. Use CalendarView Widget in xml file

Open res/layout/activity_main.xml file. Then, add below code into it.

In activity_main.xml file, we have defined calendarView widget. Now, we will access this widget in java file to perform some operations on it.

4. Access CalendarView Widget in java file

Open src/main/java/com.tutorialwing.calendarview/MainActivity.java file. Then, add below code into it.

In MainActivity.java file, we have accessed calendarView widget. Then, we have set a date change listener that shows selected date as toast message.

Since AndroidManifest.xml file is very important in any android application, we are also going to see the content inside this file.

AndroidManifest.xml

Code inside src/main/AndroidManifest.xml file is as below –

When we run the program, we will get output as shown above.

That’s end of tutorial on Android CalendarView widget.

Источник

Android calendarview get selected date

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 .

Читайте также:  Visual studio android amd

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.

Читайте также:  Android 64 bit для компьютера

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.

Источник

Оцените статью