- Android Calendar API
- Зачем!?
- Использовать недокументированное API — это ПЛОХО! Пнятненько?
- CalendarView
- Получить выбранную дату
- Программно установить дату в CalendarView
- Установить минимальную и максимальную даты
- Дополнительное чтение
- Android studio google calendar
- Java Quickstart
- Prerequisites
- Step 1: Prepare the project
- Step 2: Set up the sample
- Step 3: Run the sample
- Troubleshoot the sample
- This app isn’t verified
- Further reading
- Android Calendar View
- Android Tutorial
- Android Calendar View
- Project Structure
Android Calendar API
Зачем!?
Я столкнулся с такой задачей, когда писал приложение для составления своего университетского расписания. Удобно иметь свое расписание отдельно, да еще и стандартный календарь не поддерживает повторение событий через одну неделю, что необходимо для двухнедельного (чет./нечет.) расписания.
Идеей фикс была функция приложения, которая позволит “заполнить” введенным расписанием Android календарь. Плюсы очевидны: синхронизация с Google Calendar от google (простите за тавтологию), встроенные виджеты календаря (очень уж хорош этот виджет от HTC Sense) и гора виджетов от сторонних производителей, которые хоть покажут следующее событие, хоть загруженность недели, и т.д. Тут и понадобилась работа с календарем Android.
Использовать недокументированное API — это ПЛОХО! Пнятненько?
Неужели чтобы решить эту очевидную задачу необходимо использовать недокументированное API? Ответ – нет. Самый правильный метод использовать API Google Calendar, что я вам и советую сделать в своих разработках.
Но “правильный” метод налагает ряд ограничений:
• Нельзя использовать в отсутствии соединения с Интернет;
• Необходима синхронизация после заполнения календаря;
• Данные (а их не мало при заполнении целого года) идут до сервера а потом при синхронизации идут обратно, что, очевидно, увеличивает трафик в два раза.
По моему мнению, намного удобней использовать офлайн версию календаря, которую при любом удобном случае можно синхронизировать с гуглокалендарем. К сожалению google не позаботился о разработчиках под Android и не опубликовал официального API, но к нашей радости исходные коды Android открыты и умные люди уже давно нашли волшебные URI контент провайдеров.
Источник
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 позволяет выбрать дату, время и повторяющие интервалы.
Источник
Android studio google calendar
Сегодня мы разберем такой простой и всем известный элемент пользовательского интерфейса 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 сообщения, добавить к значению месяца единицу.
Источник
Java Quickstart
Complete the steps described in the rest of this page to create a simple Java command-line application that makes requests to the Google Calendar API.
Prerequisites
To run this quickstart, you need the following prerequisites:
- A Google account with Google Calendar enabled.
Step 1: Prepare the project
To prepare the project:
In your working directory, run the following commands to create a new project structure:
Copy the credentials.json file you downloaded as a prerequisite into the newly-created src/main/resources/ directory.
Open the default build.gradle file and replace its contents with the following code:
Step 2: Set up the sample
To set up the sample:
- In src/main/java/ , create a new Java file with a name that matches the mainClassName value in your build.gradle file.
Include the following code in your new Java file:
Step 3: Run the sample
To run the sample:
Execute the following command:
This command builds and runs the sample.
(optional). If this is your first time running the sample, the sample opens a new window prompting you to authorize access to your data:
The sample executes.
If you have problems, refer to the Troubleshoot the sample section.
Troubleshoot the sample
This section describes a common issue that you can encounter while attempting to run this quickstart.
This app isn’t verified
If the OAuth consent screen displays the warning «This app isn’t verified,» your app is requesting scopes that provide access to sensitive user data. If your application uses sensitive scopes, your your app must go through the verification process to remove that warning and other limitations. During the development phase you can continue past this warning by clicking Advanced > Go to
Further reading
For further information on the APIs used in this quickstart, refer to the following:
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Источник
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:
Источник