- Горизонтальный календарь android studio
- Horizontal CalendarView in Android
- What we are going to build in this article?
- Step by Step Implementation
- Creating A Horizontal Scrolling Calendar Using Android SDK
- A material horizontal calendar view for Android based on RecyclerView
- Horizontal Calendar
- Installation
- Prerequisites
- Usage
- Customization
- More Customizations
- Months Mode
- Events
- Reconfiguration
- Горизонтальный календарь android studio
- About
Горизонтальный календарь 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 сообщения, добавить к значению месяца единицу.
Источник
Horizontal CalendarView in Android
If we are making an application that provides services such as booking flights, movie tickets, or others we generally have to implement a calendar in our application. We have to align the calendar in such a way so that it will look better and will take less amount of space in the mobile app. Most of the apps prefer to use Horizontal Calendar View inside their which looks better than the normal calendar. In this article, we will take a look at implementing a similar calendar in our app.
What we are going to build in this article?
We will be building a simple application in which we will be simply creating a horizontal calendar and we will be displaying the whole dates of the month in it. We will be displaying these dates in the horizontal Calendar View. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Step by Step Implementation
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Источник
Creating A Horizontal Scrolling Calendar Using Android SDK
Jul 10, 2019 · 4 min read
Often we choose to use a horizontal scrolling calendar as a date picker while building new apps. Com m on examples are ordering apps where an order needs to be scheduled for a later date or a simple, OneNote sort of app with the ability to pick a date and take notes. The default calendar Widget that comes with Android Studio shows a month’s worth of dates and fills up the real-estate without much effort. What is interesting is to have the calendar widget where we can select a date and have a ListView or a similar view to display cart order for a given date.
In this horizontal scrolling calendar, I have used recyclerView, which is perhaps one of the most powerful Containers present in Android SDK. It is very flexible and extensible. However, it is usually seen as quite complex to use.
Here are the screenshot and a video link of this horizontal scrolling calendar.
Here are the features it supports.
a) It shows Sundays in Red Color for easy identification.
b) You can customize it for the number of days, presently it is for 30 days, starting at 2 days before today.
c) It has two ImageViews to control the horizontal scrolling on left and right.
d) In this example, I am using Calendar data, but you can alter it to use any other data by modifying MyCalendar and MyCalendar java files.
Using a recyclerView requires us to use the RecyclerView Adapter. The adapter is fed with data that needs to be displayed in the textViews. The adapter gets initialized from the MainActivity.
In this example, two textViews are used as Child views inside the recyclerView.
The content_main.xml contains the recyclerView and the reverse and forward ImageViews.
The date_list_row contains the TextViews to show the day of the week and time.
The month and year are also stored and can be accessed using ‘get methods’ from MyCalendar data holder. The myCalendarData generates the calendar dates based on inputs from MainActivity.
The MainActivity would call the LayoutoutManager to generate a horizontal layout instead of vertical.
The CalendarAdapter code, as shown below, has the constructor for the viewHolder and the adapter. The viewholder holds the two TextViews, which are used as childviews for each day of the calendar.
Android would call onBindViewHolder() during initializing and refresh, this helps in getting the TextView’s text set with correct values.
During view creation, CreateViewHolder() is called automatically by android, so I had to override it to LayoutInflator to get the two textViews that were to be used as ChildViews.
One interesting and challenging aspect of recyclerView is that it refreshes by default every time the screen scrolls and repaints the childViews again, this causes the index numbers to be reset internally. One of the challenges I had due to it was to identify Sundays and mark them in red. I found a simple way of doing it by overwriting the onScrolled() method in recyclerView.addOnScrollListener(). This proved to be much similar than other ways documented in the Android developer site. Here is the code snippet:-
In MainActivity, I am populating the CalendarList for 30 calendar days as described earlier.
In MainActivity onClick() and onLongClick (), methods are overwritten from recyclerView.addOnItemTouchListener to get demonstrate the clicked date can be used for further actions in the view, such as selecting an order for a shopping app, etc..
Hope you enjoyed reading this and feel free to reuse the code as required.
Источник
A material horizontal calendar view for Android based on RecyclerView
Horizontal Calendar
A material horizontal calendar view for Android based on RecyclerView.
Installation
The library is hosted on jcenter, add this to your build.gradle:
Prerequisites
The minimum API level supported by this library is API 14 (ICE_CREAM_SANDWICH).
Usage
- Add HorizontalCalendarView to your layout file, for example:
- In your Activity or Fragment, define your start and end dates to set the range of the calendar:
- Then setup HorizontalCalendar in your Activity through its Builder:
- Or if you are using a Fragment:
- To listen to date change events you need to set a listener:
- You can also listen to scroll and long press events by overriding each perspective method within HorizontalCalendarListener:
Customization
- You can customize it directly inside your layout:
- Or you can do it programmatically in your Activity or Fragment using HorizontalCalendar.Builder :
More Customizations
Months Mode
HorizontalCalendar can display only Months instead of Dates by adding mode(HorizontalCalendar.Mode.MONTHS) to the builder, for example:
Events
A list of Events can be provided for each Date which will be represented as circle indicators under the Date with:
Reconfiguration
HorizontalCalendar configurations can be changed after initialization:
- Change calendar dates range:
- Change default(not selected) items style:
- Change selected item style:
- Change formats, text sizes and selector color:
Источник
Горизонтальный календарь android studio
A material horizontal calendar view for Android based on RecyclerView .
The library is hosted on jcenter, add this to your build.gradle:
The minimum API level supported by this library is API 14 (ICE_CREAM_SANDWICH).
- Add HorizontalCalendarView to your layout file, for example:
- In your Activity or Fragment, define your start and end dates to set the range of the calendar:
- Then setup HorizontalCalendar in your Activity through its Builder:
- Or if you are using a Fragment:
- To listen to date change events you need to set a listener:
- You can also listen to scroll and long press events by overriding each perspective method within HorizontalCalendarListener:
- You can customize it directly inside your layout:
- Or you can do it programmatically in your Activity or Fragment using HorizontalCalendar.Builder :
HorizontalCalendar can display only Months instead of Dates by adding mode(HorizontalCalendar.Mode.MONTHS) to the builder, for example:
A list of Events can be provided for each Date which will be represented as circle indicators under the Date with:
HorizontalCalendar configurations can be changed after initialization:
- Change calendar dates range:
- Change default(not selected) items style:
- Change formats, text sizes and selector color:
Make sure to call horizontalCalendar.refresh(); when you finish your changes
- Disable specific dates with HorizontalCalendarPredicate , a unique style for disabled dates can be specified as well with CalendarItemStyle :
- Select a specific Date programmatically with the option whether to play the animation or not:
- Check if a date is contained in the Calendar:
- Check if two dates are equal (year, month, day of month):
- Get number of days between two dates:
Contributions are welcome, feel free to submit a pull request.
Licensed under the Apache License, Version 2.0 (the «License»); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an «AS IS» BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
About
A material horizontal calendar view for Android based on RecyclerView
Источник