Android studio календарь событий

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

Источник

Android Calendar API

Зачем!?

Я столкнулся с такой задачей, когда писал приложение для составления своего университетского расписания. Удобно иметь свое расписание отдельно, да еще и стандартный календарь не поддерживает повторение событий через одну неделю, что необходимо для двухнедельного (чет./нечет.) расписания.
Идеей фикс была функция приложения, которая позволит “заполнить” введенным расписанием Android календарь. Плюсы очевидны: синхронизация с Google Calendar от google (простите за тавтологию), встроенные виджеты календаря (очень уж хорош этот виджет от HTC Sense) и гора виджетов от сторонних производителей, которые хоть покажут следующее событие, хоть загруженность недели, и т.д. Тут и понадобилась работа с календарем Android.

Использовать недокументированное API — это ПЛОХО! Пнятненько?


Неужели чтобы решить эту очевидную задачу необходимо использовать недокументированное API? Ответ – нет. Самый правильный метод использовать API Google Calendar, что я вам и советую сделать в своих разработках.

Но “правильный” метод налагает ряд ограничений:
• Нельзя использовать в отсутствии соединения с Интернет;
• Необходима синхронизация после заполнения календаря;
• Данные (а их не мало при заполнении целого года) идут до сервера а потом при синхронизации идут обратно, что, очевидно, увеличивает трафик в два раза.

По моему мнению, намного удобней использовать офлайн версию календаря, которую при любом удобном случае можно синхронизировать с гуглокалендарем. К сожалению google не позаботился о разработчиках под Android и не опубликовал официального API, но к нашей радости исходные коды Android открыты и умные люди уже давно нашли волшебные URI контент провайдеров.

Читайте также:  Пользуются ли американцы андроид

Источник

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.

Источник

Custom Calendar View With Events Android

Custom Calendar View With Events Android

This tutorial you will learn how to create a custom calendar view with events and notifications.You can use android Calendar Instance, and you can inflate calendar days of the month by using grid layout and linear layout manager. You can use any type of database whether it is local database like SQLite and ROOM database or remote database like MySQL or Firebase database. So the calendar has flexibility to add, update and delete user`s events.

Читайте также:  Платформ тулс для андроид

The custom calendar view has been designed to allow the user to navigate through previous and next months. Also it allows the user to click on any day of the month to add new event. Custom calendar view with event also allow the user to long press on any day with added events to show the event previously added. At this point the user can delete events.

Another strong point of Custom Calendar View With Event is event alarm with notification. When the user create new event he can enable and disable the alarm for the event date. Also this the user can set alarm when he show the previously created events.

Tutorial you may interested

ViewPager with TabLayout Android Studio

How to Create SearchView in Android Studio

Setting ImageView in Android Studio

37 COMMENTS

Hi, Im having an error with the notification.
I followed the 4th video but in the end i have an error on method OnBindViewHolder is this lines:
Calendar datecalendar = Calendar.getInstance();
datecalendar.setTime(ConvertStringToDate(events.getDATE()));
final int alarmYear = datecalendar.get(Calendar.YEAR);
final int alarmMes = datecalendar.get(Calendar.MONTH);
final int alarmDia = datecalendar.get(Calendar.DAY_OF_MONTH);
Calendar timecalendar = Calendar.getInstance();
timecalendar.setTime(ConvertStringToTime(events.getTIME()));.
final int alarmHour = timecalendar.get(Calendar.HOUR_OF_DAY);
final int alarmMinute = timecalendar.get(Calendar.MINUTE);

I wrote some interrogation in the line where i have the error, It says that NullPointerException because i cannot use method setTime on a null object reference

that means that convert string ti time returns null you need to make sure that the value of events.getTIME() returns the string time, make sure that the time saved correctly in sqlite database.

I have a problem when i want to show the number of events in under the day of the month.This is my code in getView for that

TextView Day_Number = view.findViewById(R.id.calendar_day);
TextView EventNumber = view.findViewById(R.id.id_event);
Day_Number.setText(String.valueOf(DayNo));
Calendar eventCalendar = Calendar.getInstance();
ArrayList arrayList = new ArrayList();
for (int i = 0;i

    Abdelhamid AhmedJune 8, 2020 At 4:27 pm

Please can you clarify more i want to know if the app crashed or the events number is not appear and if the app crashed send me the errors from logcat.

Hello Good day, I encountered a problem where the CollectEventByDate method isn’t passing any data to display anything in the //recyclerView.setLayoutManager(layoutManager);
I did each step in the video and used try catch error to see if things works and the LongClickListener did where it displayed the event row layout. Did I trace it wrong? I’m not too sure where I messed up. I already made the RecycleView xml as well as the EventRecycler Adapter java step by step. Thanks for the feedback. The error is:

java.lang.NullPointerException: Attempt to invoke virtual method ‘void androidx.recyclerview.widget.RecyclerView.setLayoutManager(androidx.recyclerview.widget.RecyclerView$LayoutManager)’ on a null object reference

java.lang.NullPointerException: Attempt to invoke virtual method ‘void androidx.recyclerview.widget.RecyclerView.setLayoutManager(androidx.recyclerview.widget.RecyclerView$LayoutManager)’ on a null object reference

Make sure the id of the recycler view in the xml file that shows the events is the same in java file (RecyclerView recyclerView = showView.findViewById(R.id.EventsRV);).

Hello again, the id of the recycle view in xml is correct but I’m still getting the same error. I really have no idea why it’s not displaying the data, is it perhaps that the data is not saving in the database? The CollectEventsByDate method may be passing an empty data hence the null…But I’m unsure which part it stops…

Hello I solved the previous problem I had, thank you for that, but I encountered another problem with the Cursor. Here’s the error:

java.lang.IllegalStateException: Couldn’t read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.

if there are changes in create query strings upgrade the database version. else make sure the create query strings are right.

It works now, thank you so much!

Hello again, I’m getting an error whenever I set up an Alarm.

Hello again, I’m getting an error whenever I set up an Alarm. Where do I add the column ID?
android.database.sqlite.SQLiteException: no such column: ID (code 1 SQLITE_ERROR): , while compiling: SELECT ID, EVENT_NOTIFY FROM EVENT_LIST WHERE DAY=? AND EVENT_NAME=? AND TIME=?

hi, when i try to start the app it crashed
is it possible to send the hold project instead?

Please follow the steps of handle errors page, and the full source code is available in the tutorial.

Hi, I think Tutorial is brilliant, you have done a great job,
But I am facing a logical error for quite some time now so could you plz help me.
In MyGridAdapter Java class the condition where you are checking if the DAY, MONTH and YEAR of DATECALENDAR are equal to EVENTCALENDAR is basically true all the time beacause they are both Initialized as getInstace(), so every time SetUpCalendar() is called that loop is adding an event in the all the arrayList, whether that call is for DELETING event, for NEXTBTN or for PREVIOUSBTN an event is added in every arrayList.
i have read the Documentation on you rwebsite and watched this video several time, could you plz look it up.
Thank you

Читайте также:  Unity android package name

Here is my Grid Adapter Code

public class DateGridAdapter extends ArrayAdapter <
List dates;
Calendar currentDate;
List events;
LayoutInflater inflater;

public DateGridAdapter(@NonNull Context context, List dates, Calendar currentDate, List events) <
super(context, R.layout.single_cell);

this.dates=dates;
this.currentDate=currentDate;
this.events=events;
inflater = LayoutInflater.from(context);
>

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) <
Date monthDate = dates.get(position);
Calendar dateCalendar = Calendar.getInstance();
dateCalendar.setTime(monthDate);
int DayNo = dateCalendar.get(Calendar.DAY_OF_MONTH);
int displayMonth = dateCalendar.get(Calendar.MONTH)+1;
int displayYear = dateCalendar.get(Calendar.YEAR);
int currentMonth = currentDate.get(Calendar.MONTH)+1;
int currentYear = currentDate.get(Calendar.YEAR);

View view = convertView;
if (view ==null) <
view = inflater.inflate(R.layout.single_cell,parent,false);

TextView Day_Number = view.findViewById(R.id.calendar_day);
TextView EventNumber = view.findViewById(R.id.events_id);
Day_Number.setText(String.valueOf(DayNo));
Calendar eventCalendar = Calendar.getInstance();
ArrayList arrayList = new ArrayList();
for (int i = 0;i
Sian July 15, 2020 At 12:26 pm

I keep having an issue with the ReadEventsperMonth method. My logcat says

android.database.sqlite.SQLiteException: no such column: event (code 1 SQLITE_ERROR): , while compiling: SELECT event, time, date, month, year FROM eventstable WHERE month=? and year =?

and I have checked the syntax of the String Selection and it seems to be correct but I still can’t get it to work. Could you help?

Thanks, man for this nice tutorial. I want to highlight the current date of the month in the Gridview just like the android calendar. Where I have to add code for the current day.

add variable of current day from current date
int currentDay = currentDate.get(Calendar.DAY_OF_MONTH);
then add another conditon
if(displayMonth == currentMonth && displayYear == currentYear) <
view.setBackgroundColor(getContext().getResources().getColor(R.color.green));

> else if(DayNo == currentDay) <
view.setBackgroundColor(getContext().getResources().getColor(android.R.color.holo_orange_dark));
>
else
<
view.setBackgroundColor(Color.parseColor(“#cccccc”));
>

Hey, so when the app launches the events are on the calendar. If I go to another activity and back the events disappear until the next time the app is launched. How would I correct this?

Very nice setup. However, when I leave the activity and come back the events are gone. Is there a way to fix this without having the user exit the app and go back in?

Hi! I have a problem with the show events activity.
I had working the app but then I made changes in the data base to add new variables and now I can,t see anything in the row_layout when I press the screen. Only a white row.
I read again and again de cde but it seems everything It,s ok.
I also updated the version of the db, but stil not working.

make sure that data saved to the right columns in the database. open emulator and try to add events. the open android device monitor to extract the database file to desktop, install DB browser for SQLite application that helps you to show the data in the database. if events data saved to wrong columns it is expected to collect zero rows.
this video helps you how to extract database.
https://youtu.be/7Ua98YBJF50

Ok thaks I’ll try It yo see If It works.
Thank you!

Looks like the database is empty in sqlite admin. Which could be the error?
It´s my first database and I,m a little lost

I have checked the database with db browser and the columns get the information. But aren`t in order and don´t know why. I think I write the new columns in the right order, right below the existing ones.
Is it possible to reorder the columns without making a new data base? And how can I do that?

Hello, I have followed this tutorial but I have a problem, which is “java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.widget.TextView.setText(java.lang.CharSequence)’ on a null object reference” This error only occurs when you want to see the events on a day that has events, what can be the problem?

I found the error, it was that the inflate addressed the wrong one, thanks 🙂

I’m glad that the problem was solved!
If you have other questions, just let me know!

sir if this application is running for you, could you please send me the zip file at rimshafaisal.246@gmail.com
my app is getting crashed, i don’t know why, i have followed every step.
i would really appreciate it if you could help me out.

Assalamuallikum,
great video sir,

My app getting crashed
i have copied your code just like in videos,but following are my problems:

at main activity.xml:

after writing this code i cannt got any layout ,i have added all dependency as you have written

and also:
in Customcalenderview:
Log.d(TAG, “getRequestCode: “+code);

i am having error saying,that Tag has not initialized.

Источник

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