<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sevdetneng on Medium]]></title>
        <description><![CDATA[Stories by Sevdetneng on Medium]]></description>
        <link>https://medium.com/@sevdetneng?source=rss-18e58bcdb604------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*DyEYEjWJZ2Wd35tiIL6rEg.jpeg</url>
            <title>Stories by Sevdetneng on Medium</title>
            <link>https://medium.com/@sevdetneng?source=rss-18e58bcdb604------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 13:49:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sevdetneng/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Custom Calendar With Events In Android]]></title>
            <link>https://medium.com/@sevdetneng/custom-calendar-with-events-in-android-35f32a1e1044?source=rss-18e58bcdb604------2</link>
            <guid isPermaLink="false">https://medium.com/p/35f32a1e1044</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[calendar-view]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-development]]></category>
            <dc:creator><![CDATA[Sevdetneng]]></dc:creator>
            <pubDate>Wed, 24 Jan 2024 12:42:20 GMT</pubDate>
            <atom:updated>2024-01-24T12:42:20.188Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello dear developers,</p><p>Recently I’ve been working on an app and encountered an issue where I needed to highlight some specific days in a <strong>calendar view</strong> that had <strong>events.</strong></p><p>As you may know, the default calendar view that comes with the Android SDK doesn’t have any capability like this and since I didn’t want to use any third-party libraries, all that remained was creating a <strong>custom calendar view</strong> for my needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*LTPvQVVFf_KNuQvvBr4hUg.gif" /><figcaption><strong>Custom Calendar View</strong></figcaption></figure><p>In this writing, I am going to share with you how I created a solution for my project, with the hope that it may provide some insights into such a matter.</p><p>Before diving into the code, I would like to give some information about <strong>Calendar</strong> class which I frequently use in this project.</p><p>As the official <a href="https://developer.android.com/reference/kotlin/android/icu/util/Calendar"><strong>Android</strong> </a>document says,</p><blockquote>Calendar is an abstract base class for converting between a Date object and a set of integer fields such as YEAR, MONTH, DAY, HOUR, and so on.</blockquote><p>We will primarily utilize this class to retrieve information such as <strong>Day of the Month</strong>, <strong>Day of the Week</strong>, <strong>Month</strong>, and <strong>Year</strong> from a given Date object.</p><p>Let’s start by creating a Calendar object,</p><pre>// Create a new instance of a Calendar object.<br>val calendar = Calendar.getInstance()</pre><p>By default, when we create a new Calendar instance, it starts with <strong>today’s date</strong>. After learning the basics of Calendar class, lets move forward.</p><p>In this approach, I utilized <strong>RecyclerView</strong> with the assistance of <strong>PagerSnapHelper</strong> to create a swipeable monthly calendar.</p><p>Firstly, I’ve created a new fragment called RecyclerViewFragment and inside that fragment I’ve created a new calendar object as I’ve mentioned before. After that, I used that calendar instance to create a starting list for my calendar. This list includes <strong>11 months</strong> in total. At the center we have the <strong>current month</strong>, at the start of the list we have <strong>5 months before</strong> the current month and at the and of the list we have <strong>5 months after</strong> the current month. And lastly, I’ve created a variable called <strong>selectedMonthDate</strong> to keep track of the currently displayed month on the screen.</p><pre>class RecyclerViewFragment : BaseFragment&lt;FragmentRecyclerViewBinding&gt;(FragmentRecyclerViewBinding::inflate) {<br>    private val loadedDates : MutableList&lt;Date&gt; = mutableListOf()<br>    private var selectedMonthDate : Date? = null<br><br>    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {<br>        val calendar = Calendar.getInstance()<br>        // Start from the current month<br>        selectedMonthDate = calendar.time<br>        // Initiate the months list<br>        startList()<br>    }<br><br>    private fun startList(){<br>            // Initiate the calendar months list<br>            val calendar = Calendar.getInstance()<br>            calendar.time = selectedMonthDate!!<br>            val currentDate = calendar.time<br>    <br>            // Add 5 months before current month<br>            for(i in -5..-1){<br>                calendar.add(Calendar.MONTH,i)<br>                loadedDates.add(calendar.time)<br>                calendar.time = currentDate<br>            }<br>            // Add current month<br>            loadedDates.add(currentDate)<br>            calendar.time = currentDate<br>            // Add 5 months after current month<br>            for(i in 1..5){<br>                calendar.add(Calendar.MONTH,i)<br>                loadedDates.add(calendar.time)<br>                calendar.time = currentDate<br>            }<br>      }<br> <br>}</pre><p>After creating the list, lets create the UI for calendar. For the general calendar view, I’ve used a <strong>RecyclerView </strong>for displaying the months, a <strong>TextView</strong> for displaying the selected year and the month, two<strong> ImageViews</strong> as previous and next month buttons and some TextViews inside a <strong>LinearLayout</strong> to display days of the week.</p><pre>&lt;!-- fragment_recycler_view.xml --&gt;<br><br>&lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    tools:context=&quot;.presentation.ui.RecyclerViewFragment&quot;&gt;<br><br><br>    &lt;TextView<br>        android:id=&quot;@+id/monthText&quot;<br>        android:layout_width=&quot;0dp&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_marginTop=&quot;48dp&quot;<br>        android:gravity=&quot;center&quot;<br>        android:text=&quot;TextView&quot;<br>        android:textSize=&quot;18sp&quot;<br>        android:textStyle=&quot;bold&quot;<br>        app:layout_constraintEnd_toStartOf=&quot;@+id/nextMonth&quot;<br>        app:layout_constraintStart_toEndOf=&quot;@+id/previousMonth&quot;<br>        app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;<br><br>    &lt;ImageView<br>        android:id=&quot;@+id/previousMonth&quot;<br>        android:layout_width=&quot;35dp&quot;<br>        android:layout_height=&quot;35dp&quot;<br>        android:layout_marginStart=&quot;48dp&quot;<br>        android:src=&quot;@drawable/baseline_arrow_back_ios_new_24&quot;<br>        app:layout_constraintBottom_toBottomOf=&quot;@+id/monthText&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintTop_toTopOf=&quot;@+id/monthText&quot; /&gt;<br><br>    &lt;ImageView<br>        android:id=&quot;@+id/nextMonth&quot;<br>        android:layout_width=&quot;35dp&quot;<br>        android:layout_height=&quot;35dp&quot;<br>        android:layout_marginEnd=&quot;48dp&quot;<br>        android:src=&quot;@drawable/baseline_arrow_forward_ios_24&quot;<br>        app:layout_constraintBottom_toBottomOf=&quot;@+id/monthText&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>        app:layout_constraintTop_toTopOf=&quot;@+id/monthText&quot; /&gt;<br><br>    &lt;LinearLayout<br>        android:id=&quot;@+id/linearLayout&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_marginTop=&quot;48dp&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintTop_toBottomOf=&quot;@id/monthText&quot;<br>        android:gravity=&quot;center&quot;<br>        android:orientation=&quot;horizontal&quot;&gt;<br><br>        &lt;TextView<br>            android:layout_width=&quot;0dp&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:layout_weight=&quot;1&quot;<br>            android:gravity=&quot;center&quot;<br>            android:text=&quot;MON&quot;<br>            android:textSize=&quot;14sp&quot; /&gt;<br><br>        &lt;TextView<br>            android:layout_width=&quot;0dp&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:layout_weight=&quot;1&quot;<br>            android:gravity=&quot;center&quot;<br>            android:text=&quot;TUE&quot;<br>            android:textSize=&quot;14sp&quot; /&gt;<br><br>        &lt;!-- Repeat till SUNDAY --&gt;<br><br>    &lt;/LinearLayout&gt;<br><br>    &lt;androidx.recyclerview.widget.RecyclerView<br>        android:id=&quot;@+id/pageRecyclerView&quot;<br>        android:layout_width=&quot;0dp&quot;<br>        android:layout_height=&quot;0dp&quot;<br>        android:layout_marginTop=&quot;4dp&quot;<br>        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintTop_toBottomOf=&quot;@+id/linearLayout&quot; /&gt;<br>&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;</pre><p>After creating the general calendar view, I’ve created another <strong>XML</strong> file for displaying the current month. I’ve called it <strong>page_recycler_item</strong> and it only has a single <strong>RecyclerView</strong> in it. We’re going to utilize this <strong>RecyclerView</strong> to display all of the days of the selected month.</p><pre>&lt;!-- page_recycler_item.xml --&gt;<br><br>&lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;&gt;<br><br>    &lt;androidx.recyclerview.widget.RecyclerView<br>        android:id=&quot;@+id/daysRecycler&quot;<br>        android:layout_width=&quot;0dp&quot;<br>        android:layout_height=&quot;0dp&quot;<br>        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;<br>&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;</pre><p>After creating the RecyclerView, we are going to create another XML file called <strong>calendar_cell.xml.</strong> In this XML file, we are going to create the <strong>UI</strong> of the calendar cells.</p><pre>&lt;!-- calendar_cell.xml --&gt;<br><br>&lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;wrap_content&quot;<br>    android:layout_gravity=&quot;center&quot;&gt;<br><br>    &lt;androidx.constraintlayout.widget.ConstraintLayout<br>        android:id=&quot;@+id/backgroundConstraint&quot;<br>        android:layout_width=&quot;50dp&quot;<br>        android:layout_height=&quot;30dp&quot;<br>        android:layout_marginBottom=&quot;4dp&quot;<br>        android:background=&quot;@drawable/calendar_cell_background&quot;<br>        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintTop_toTopOf=&quot;parent&quot;&gt;<br><br>        &lt;TextView<br>            android:id=&quot;@+id/textView&quot;<br>            android:layout_width=&quot;wrap_content&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:text=&quot;1&quot;<br>            android:textSize=&quot;10sp&quot;<br>            app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>            app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>            app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>            app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;<br>    &lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;<br>&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;</pre><p>As you can see, this XML file consists of two elements, a <strong>ConstraintLayout</strong> inside the root constraint and a <strong>TextView</strong> to display the day. We are going to utilize inner constraint to change the background view of the calendar cells to highlight different background styles for different days. For example, for days that have <strong>events</strong>, we are going to display a <strong>purple-colored</strong> background; for <strong>today’s</strong> cell, we will use a <strong>blue-colored</strong> background, and for the <strong>rest of the month</strong>, an <strong>orange-colored</strong> background will be displayed.</p><pre>&lt;!-- calendar_cell_today.xml --&gt;<br><br>&lt;selector xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;<br>    &lt;item android:state_selected=&quot;true&quot; android:drawable=&quot;@drawable/calendar_today_selected&quot;/&gt;<br>    &lt;item android:state_selected=&quot;false&quot; android:drawable=&quot;@drawable/calendar_today_unselected&quot;/&gt;<br>&lt;/selector&gt;</pre><pre>&lt;!-- calendar_today_selected.xml --&gt;<br><br>&lt;shape xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;<br>    &lt;solid android:color=&quot;#61BDC1&quot;/&gt;<br>    &lt;corners android:radius=&quot;10dp&quot;/&gt;<br>    &lt;stroke android:width=&quot;2dp&quot; android:color=&quot;#61BDC1&quot;/&gt;<br>&lt;/shape&gt;</pre><pre>&lt;!-- calendar_today_unselected.xml --&gt;<br><br>&lt;shape xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;<br>    &lt;solid android:color=&quot;#FFFFFF&quot;/&gt;<br>    &lt;corners android:radius=&quot;10dp&quot;/&gt;<br>    &lt;stroke android:width=&quot;2dp&quot; android:color=&quot;#61BDC1&quot;/&gt;<br>&lt;/shape&gt;</pre><p>As you can see I’ve created three more XML files for the display today’s cell on the calendar. <strong>calendar_cell_today.xml</strong> is a selector <strong>XML</strong> file which has two items, one for <strong>state_selected = true</strong> and another for <br><strong>state_selected = false</strong>. We are going to switch between these states to manipulate the selected day view. We will be needing three more selector XML files which are called;</p><ul><li><strong><em>calendar_cell_background.xml</em></strong><em> for the normal days of the month.</em></li><li><strong><em>calendar_cell_event.xml</em></strong><em> for displaying the days that has events.</em></li><li><strong><em>calendar_cell_gray.xml</em></strong><em> for displaying the days of the previous and next months.</em></li></ul><p>As the purpose of this writing, I am not going to share <strong>XML</strong> files for these selectors but they follow the same structure as <strong>calendar_cell_today.xml </strong>so you can play around with it and create them on your own.</p><p>After creating XML files, now lets create a <strong>ListAdapter </strong>for the inner RecyclerView. This adapter will be called CalendarAdapter and it will be utilized to display day cells in a <strong>GridLayoutManager</strong>. Lets start by creating the base class.</p><pre>// CalendarAdapter.kt<br><br>class CalendarAdapter(<br>    val events: List&lt;Date&gt;,<br>    val context: Context,<br>    val selectedDate: Date?,<br>    val currentMonth: Date,<br>    val onItemClick: (CalendarDay) -&gt; Unit<br>) : ListAdapter&lt;CalendarDay, CalendarAdapter.ViewHolder&gt;(CalendarDiffCallBack()) {<br><br>    inner class ViewHolder(private val binding: CalendarCellBinding) :<br>        RecyclerView.ViewHolder(binding.root) {<br>        <br>        fun bind(date : calendarDay){<br>          // Will write UI logic here<br>        }<br>    }<br><br>    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {<br>        val binding =<br>            CalendarCellBinding.inflate(LayoutInflater.from(parent.context), parent, false)<br>        return ViewHolder(binding)<br>    }<br><br>    override fun onBindViewHolder(holder: ViewHolder, position: Int) {<br>        holder.bind(getItem(position))<br>    }<br>}<br><br>class CalendarDiffCallBack() : DiffUtil.ItemCallback&lt;CalendarDay&gt;() {<br>    override fun areItemsTheSame(oldItem: CalendarDay, newItem: CalendarDay): Boolean {<br>        return oldItem == newItem<br>    }<br><br>    override fun areContentsTheSame(oldItem: CalendarDay, newItem: CalendarDay): Boolean {<br>        return oldItem == newItem<br>    }<br><br>}</pre><p>As you can see, this class has five parameters, 4 of them are variables and one is a function parameter. <strong><em>events</em></strong> parameter is the list of events as a list of <strong>Date</strong> objects. <strong><em>context</em></strong> parameter will be used for switching different <strong>drawable</strong> backgrounds for different days. <strong><em>selectedDate</em></strong> is a <strong>nullable</strong> <strong>Date</strong> object parameter and will be used for single day selection. <strong><em>currentMonth</em></strong> parameter will be used for retrieving the displayed month information and lastly, <strong><em>onItemClick</em></strong> function will be called when we click a day cell within displayed month. When this function called, it returns a <strong>CalendarDay</strong> object.</p><p><strong>CalendarDay</strong> is a data class that I’ve created to store a specific date along with the <strong>DayOfTheMonth</strong> value for that day, simplifying the process of displaying days.</p><pre>// CalendarDay.kt<br><br>data class CalendarDay(<br>    val dayOfMonth : String,<br>    val date : Date<br>)</pre><p>Before creating the logic for our adapter, we need two more helper functions. These functions will be called <strong><em>areDatesEqual</em></strong> and <strong><em>isInTheSelectedMonth</em></strong>.</p><p>areDatesEqual function will compare two <strong>Date </strong>objects and return if they are the <strong>same day or not</strong>, isInTheSelectedMonth function will compare two <strong>Date </strong>objects and return if they are in the <strong>same month</strong> <strong>or not</strong>.</p><pre>fun areDatesEqual(dateFirst: Date, dateSecond: Date): Boolean {<br>        val sdf = SimpleDateFormat(&quot;yyyyMMdd&quot;, Locale.getDefault())<br>        return sdf.format(dateFirst).equals(sdf.format(dateSecond))<br>    }<br><br>fun isInTheSelectedMonth(dateFirst: Date, dateSecond: Date): Boolean {<br>    val sdf = SimpleDateFormat(&quot;yyyyMM&quot;, Locale.getDefault())<br>    return sdf.format(dateFirst).equals(sdf.format(dateSecond))<br>}</pre><p>As you can see, I’ve used <strong>SimpleDateFormat</strong> objects to compare two Date objects. As the official <a href="https://developer.android.com/reference/kotlin/android/icu/text/SimpleDateFormat">Android </a>document says,</p><blockquote>SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. It allows for formatting (date -&gt; text), parsing (text -&gt; date), and normalization.</blockquote><p>With the help of <strong>SimpleDateFormat </strong>we are going to convert the specific values we need from <strong>Date</strong> objects into a <strong>String</strong> and check if the two Strings are <strong>equal</strong> or not. With this method, we can easily compare if two Date objects are in the same <strong>day</strong>, <strong>month</strong>, <strong>year</strong> or even <strong>hour</strong>.</p><p>After creating the base of <strong>CalendarAdapter</strong> class and our helper functions, now lets create the <strong>logic</strong> behind the UI. Inside the <strong>bind</strong> function of <strong>ViewHolder</strong> inner class, we are going to create our logic.</p><pre>fun bind(date: CalendarDay) {<br>            if (isInTheSelectedMonth(date.date, currentMonth)) {<br>                binding.root.setOnClickListener {<br>                    // only click current month days<br>                    onItemClick(date)<br>                }<br><br>                val calendar = Calendar.getInstance()<br>                // if date is inside the selected month, set background resource<br>                if (areDatesEqual(calendar.time, date.date)) {<br>                    // Today<br>                    binding.backgroundConstraint.background =<br>                        ContextCompat.getDrawable(context, R.drawable.calendar_cell_today)<br>                } else {<br>                    var isEventDay = false<br>                    events.forEach {<br>                        if (areDatesEqual(it, date.date)) {<br>                            isEventDay = true<br>                            return@forEach<br>                        }<br>                    }<br>                    if (isEventDay) {<br>                        // event day<br>                        binding.backgroundConstraint.background =<br>                            ContextCompat.getDrawable(context, R.drawable.calendar_cell_event)<br>                    } else {<br>                        // normal day<br>                        binding.backgroundConstraint.background =<br>                            ContextCompat.getDrawable(context, R.drawable.calendar_cell_background)<br>                    }<br>                }<br>            } else {<br>                // if not in the selected month, display gray<br>                binding.backgroundConstraint.background =<br>                    ContextCompat.getDrawable(context, R.drawable.calendar_cell_gray)<br>                binding.textView.setTextColor(Color.parseColor(&quot;#D3D3D3&quot;))<br>            }<br>            binding.textView.text = date.dayOfMonth<br>             <br>            // Display the selectedDate<br>            if (selectedDate != null) {<br>                binding.backgroundConstraint.isSelected = areDatesEqual(selectedDate, date.date)<br>            }<br>        }</pre><p>Inside our logic, <br>With the help of <strong>Calendar</strong>, I’ve retrieved the Date object with the <strong>current date </strong>and used it to compare if the displayed day is the current day or not.</p><ul><li>If it’s current day, then we are going to change its <strong>background</strong> of the displayed cell to <strong>calendar_cell_today.xml.</strong></li><li>If it’s current month but not current day, then we are going to check if there are any <strong>events</strong> in the related day by iterating through the events list parameter.</li><li>If we find an event then we are going to change the <strong>background </strong>of the displayed cell to <strong>calendar_cell_event.xml </strong>if no events are found, then we are going to change the <strong>background</strong> of the cell to <strong>calendar_cell_background.xml.</strong></li><li>And lastly, if the displayed day is not in the current month, then we are going to change its <strong>background</strong> to <strong>calendar_cell_gray.xml.</strong></li></ul><p>This was the adapter we will use for the RecyclerView <strong>inside</strong> our main RecyclerView. So for the main RecyclerView’s adapter, we are going to create a class called <strong>PageAdapter </strong>which is a <strong>ListAdapter </strong>aswell<strong>.</strong></p><pre>class PageAdapter(val context: Context, val events: List&lt;Date&gt;,val onItemClick : (date : Date?) -&gt; Unit) :<br>    ListAdapter&lt;Date, PageAdapter.ViewHolder&gt;(PageAdapterDiffCallback()) {<br>    var selectedDate: Date? = null<br>    var selectedMonthPos: Int? = null<br><br>    inner class ViewHolder(private val binding: PageRecyclerItemBinding) :<br>        RecyclerView.ViewHolder(binding.root) {<br><br>        fun bind(date : Date){<br><br>        }<br>    }<br><br>    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {<br>        val binding =<br>            PageRecyclerItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)<br>        val vh = ViewHolder(binding)<br>        return vh<br>    }<br><br>    override fun onBindViewHolder(holder: ViewHolder, position: Int) {<br>        holder.bind(getItem(position))<br>    }<br>}<br><br>class PageAdapterDiffCallback() : DiffUtil.ItemCallback&lt;Date&gt;() {<br>    override fun areItemsTheSame(oldItem: Date, newItem: Date): Boolean {<br>        return oldItem == newItem<br>    }<br><br>    override fun areContentsTheSame(oldItem: Date, newItem: Date): Boolean {<br>        return oldItem == newItem<br>    }<br><br>}</pre><p>After creating the base of our adapter, we are going to create several <strong>helper functions</strong> inside our adapter.</p><p>Firstly, we are going to create the same function called areDatesEqual we created before inside the CalendarAdapter with a little tweak this time.</p><pre>fun areDatesEqual(dateFirst: Date?, dateSecond: Date?): Boolean {<br>    // Function to compare two dates are the same day<br>    val sdf = SimpleDateFormat(&quot;yyyyMMdd&quot;, Locale.getDefault())<br>    if (dateFirst == null || dateSecond == null) {<br>        return false<br>    }<br>    return sdf.format(dateFirst).equals(sdf.format(dateSecond))<br>}</pre><p>This time, as you can see our parameters are nullable. This is because we want to compare a <strong>nullable Date </strong>object.</p><p>Next, we are going to create a function called <strong>getItemPos</strong> which is going to <strong>return</strong> the <strong>position</strong> of an item within the adapter’s currentList.</p><pre>fun getItemPos(date: Date): Int {<br>    var selectedDate: Date? = null<br>    currentList.forEach {<br>        if (areDatesEqual(it, date)) {<br>            selectedDate = it<br>            return@forEach<br>        }<br>    }<br>    return currentList.indexOf(selectedDate)<br>}</pre><p>Next, we are going to create another function called, <strong>getItemByPos</strong> which is going to <strong>return</strong> an<strong> item</strong> inside the currentList by its position.</p><pre>fun getItemByPos(pos: Int): Date {<br>    return currentList[pos]<br>}</pre><p>And lastly, we are going to create our last helper function called daysInMonthList. Function creates a monthly days list for the given date. This is where most of the magic happens, so be sure to understand the logic behind it thoroughly.</p><pre>fun daysInMonthList(date: Date): List&lt;CalendarDay&gt; {<br>    val daysInMonthList: MutableList&lt;CalendarDay&gt; = mutableListOf()<br>    val calendar = Calendar.getInstance()<br>    calendar.time = date<br>    calendar.set(Calendar.DAY_OF_MONTH, 1)<br>    val dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 2<br>    when(dayOfWeek){<br>        -1 -&gt; {<br>            // SUNDAY<br>            calendar.add(Calendar.DAY_OF_MONTH,-6)<br>            while(daysInMonthList.size &lt; 42){<br>                daysInMonthList.add(CalendarDay(<br>                    calendar.get(Calendar.DAY_OF_MONTH).toString(),<br>                    calendar.time<br>                ))<br>                calendar.add(Calendar.DAY_OF_MONTH,1)<br>            }<br>        }<br>        else -&gt; {<br>            // OTHER DAYS<br>            calendar.add(Calendar.DAY_OF_MONTH,-dayOfWeek)<br>            while(daysInMonthList.size &lt; 42){<br>               daysInMonthList.add(CalendarDay(<br>                   calendar.get(Calendar.DAY_OF_MONTH).toString(),<br>                    calendar.time<br>                ))<br>                calendar.add(Calendar.DAY_OF_MONTH,1)<br>            }<br>        }<br>    }<br>    return daysInMonthList<br>}</pre><p>Basically, we are creating a list of <strong>CalendarDay </strong>objects in a monthly view. First of all we are taking the days of the last month as we need depending on the start of the current month, and then we are adding days till we hit the fourty-two days mark.</p><p>And lastly, we are creating our single selection logic inside our <strong>ViewHolder’s bind </strong>function.</p><pre>fun bind(date: Date) {<br><br>    // Get the month for the given date<br>    val list = daysInMonthList(date)<br><br>    val adapter = CalendarAdapter(events, context, selectedDate, date) { calendarDay -&gt;<br><br>        // Single selection<br>        // If clicked on the selected day, unselect<br>        if (areDatesEqual(selectedDate, calendarDay.date)) {<br>            val lastPos = selectedMonthPos<br>            selectedMonthPos = null<br>            selectedDate = null<br>            notifyItemChanged(lastPos!!)<br>        } else {<br><br>            // If clicked on an unselected day, select<br>            // If not selected a day before, select<br>            if (selectedMonthPos == null) {<br>                selectedMonthPos = adapterPosition<br>                selectedDate = calendarDay.date<br>            } else {<br><br>                // If already selected a day before, switch the selected date<br>                notifyItemChanged(selectedMonthPos!!)<br>                selectedMonthPos = adapterPosition<br>                selectedDate = calendarDay.date<br>            }<br>            notifyItemChanged(selectedMonthPos!!)<br>            onItemClick(selectedDate)<br>        }<br>    }<br>    binding.apply {<br>        daysRecycler.layoutManager = GridLayoutManager(context, 7)<br>        daysRecycler.adapter = adapter<br>        daysRecycler.itemAnimator = null<br>    }<br>    adapter.submitList(list)<br>}</pre><p>After we’re done with both adapters, we are returning to the <strong>RecyclerViewFragment </strong>for the <strong>final </strong>touches. Previously we’ve created our initial months list and a few variables inside this fragment. Now we are going to use all of the things we have created till here and make this calendar functional.</p><p>Firstly, we are going to create another variable called latestPos to save last visible month’s position. We will utilize this variable to scroll back to the latest position when we add more months to the list. Next, we are going to create our helper functions.</p><pre>private fun loadPreviousMonths(){<br>    val calendar = Calendar.getInstance()<br>    calendar.time = loadedDates[0]<br><br>    // Load the previous year<br>    for(i in 1..12){<br>       calendar.add(Calendar.MONTH,-1)<br>       loadedDates.add(calendar.time)<br>    }<br>    // Sort by time<br>    latestPos += 12<br>    loadedDates.sort()<br>}<br>private fun loadNextMonths(){<br>    val calendar = Calendar.getInstance()<br>    calendar.time = loadedDates.last()<br><br>    // Load the next year<br>    for(i in 1..12){<br>        calendar.add(Calendar.MONTH,1)<br>        loadedDates.add(calendar.time)<br>    }<br>    // Sort by time<br>    loadedDates.sort()<br>}</pre><p>When we reach the <strong>end </strong>of the list in any direction, we are going to <strong>add </strong>more months into the list with the help of these functions.</p><p>inside this logic,</p><ul><li>We are going to set the <strong>latestPos </strong>as the <strong>center </strong>of the list and then we are going to attach a <strong>PagerSnapHelper</strong> into our main <strong>RecyclerView</strong> to make it act like a <strong>Pager</strong>.</li><li>We are going to add a <strong>scrollStateListener </strong>to our RecyclerView. Inside this listener, we are going to <strong>update </strong>the <strong>latestPos </strong>variable and then determine if we are at the end of the list or not.</li><li>If we have reached the end of the list in any direction, then we are going to <strong>add </strong>more months into our list with the help of our functions.</li><li>After every addition we are going to <strong>scroll back</strong> to the <strong>same month</strong> that we were displaying before the addition.</li></ul><pre>override fun onViewCreated(view: View, savedInstanceState: Bundle?) {<br>    val calendar = Calendar.getInstance()<br><br>    // Start from the current month<br>    selectedMonthDate = calendar.time<br>    binding.monthText.text = dateFormatter(selectedMonthDate!!)<br><br>    // Initiate the months list<br>    startList()<br><br>    // Start from the center of the list<br>    latestPos = loadedDates.size/2<br><br>    // Create dummy events list<br>   val events = mutableListOf&lt;Date&gt;()<br>    for(i in 1..10){<br>        calendar.add(Calendar.DATE,i)<br>        events.add(calendar.time)<br>    }<br><br>    val adapter = PageAdapter(requireContext(),events){<br>        val sdf = SimpleDateFormat(&quot;EE dd/MM/yyyy&quot;,Locale.getDefault())<br>        Toast.makeText(requireContext(),&quot;Selected date is : ${sdf.format(it)}&quot;,Toast.LENGTH_LONG).show()<br>    }<br>    binding.pageRecyclerView.adapter = adapter<br>    binding.pageRecyclerView.itemAnimator = null<br>    adapter.submitList(loadedDates)<br>    val layoutManager = LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL,false)<br>    binding.pageRecyclerView.layoutManager = layoutManager<br><br>    // Add PagerSnapHelper to make RecyclerView scroll like a Pager<br>    val snapHelper = PagerSnapHelper()<br>    snapHelper.attachToRecyclerView(binding.pageRecyclerView)<br><br>    // Start calendar from the current month<br>    binding.pageRecyclerView.scrollToPosition(adapter.getItemPos(selectedMonthDate!!))<br><br>    binding.pageRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener(){<br>        override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {<br>            super.onScrollStateChanged(recyclerView, newState)<br>            if(newState == RecyclerView.SCROLL_STATE_IDLE){<br>                // Get the position of the selected month<br>                val pos = layoutManager.findFirstVisibleItemPosition()<br><br>                // If switched to a different month<br>                if(latestPos != pos){<br>                    // Assign new selected date<br>                    selectedMonthDate = adapter.getItemByPos(pos)<br>                    binding.monthText.text = dateFormatter(selectedMonthDate!!)<br>                    // Assign new latest position<br>                    latestPos = pos<br><br>                    // If at the start of the list, load previous months and scroll back to the same month<br>                    if(pos == 0){<br>                        loadPreviousMonths()<br>                        adapter.submitList(loadedDates.toMutableList())<br>                        recyclerView.scrollToPosition(adapter.getItemPos(selectedMonthDate!!))<br>                    }<br>                    // If at the end of the list, load next months and scroll back to the same month<br>                    if(pos == loadedDates.size-1){<br>                        loadNextMonths()<br>                        adapter.submitList(loadedDates.toMutableList())<br>                        recyclerView.scrollToPosition(adapter.getItemPos(selectedMonthDate!!))<br>                    }<br>                }<br>            }<br>        }<br>    })<br>    binding.nextMonth.setOnClickListener{<br>        // Go to the next month<br>        if(latestPos +1 &lt;= loadedDates.size-1)<br>            binding.pageRecyclerView.smoothScrollToPosition(latestPos+1)<br>    }<br>    binding.previousMonth.setOnClickListener {<br>        // Go to the previous month<br>        if(latestPos - 1 &gt;= 0){<br>            binding.pageRecyclerView.smoothScrollToPosition(latestPos-1)<br>        }<br>    }<br>    super.onViewCreated(view, savedInstanceState)<br>}</pre><p>After putting everything together, now our calendar must be working properly. As you can see this was just a template for my needs and you can alter the calendar anyway you like it.</p><p>You can find the complete source code in my github,<br><a href="https://github.com/SevdetNeng/CustomCalendarWithEvents">https://github.com/SevdetNeng/CustomCalendarWithEvents</a></p><p>This marks the conclusion of my first medium article. If you’ve reached this point, I sincerely appreciate your time. As an aspiring Android Developer, I am eager to learn something new everyday and hope this article had something new in it for you.</p><p>If you have improvements to my code or any other suggestions, please feel free to leave a comment, and see you on the next one!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35f32a1e1044" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>