Calendar View App in Android with Kotlin
Last Updated :
29 Aug, 2022
Calendar View is seen in most travel booking applications in which the user has to select the date of the journey. For the selection of the date, this view is used. In this article, we will take a look at How to implement Calendar View within our Android application using Kotlin. A sample video is given below to get an idea about what we are going to do in this article.
Note: If you want to implement Calendar View in Android applications using Java. Check out the following article: Calendar View application in Android using Java.
Step by Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail.
XML
<? xml version = "1.0" encoding = "utf-8" ?>
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity" >
< TextView
android:id = "@+id/idTVDate"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_margin = "8dp"
android:gravity = "center"
android:padding = "8dp"
android:text = "Current Date"
android:textAlignment = "center"
android:textColor = "@color/black"
android:textSize = "20sp"
android:textStyle = "bold" />
< CalendarView
android:id = "@+id/calendarView"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_below = "@id/idTVDate"
android:layout_marginTop = "30dp" />
</ RelativeLayout >
|
Step 3: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
package com.gtappdevelopers.kotlingfgproject
import android.os.Bundle
import android.widget.CalendarView
import android.widget.CalendarView.OnDateChangeListener
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
lateinit var dateTV: TextView
lateinit var calendarView: CalendarView
override fun onCreate(savedInstanceState: Bundle?) {
super .onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
dateTV = findViewById(R.id.idTVDate)
calendarView = findViewById(R.id.calendarView)
calendarView
.setOnDateChangeListener(
OnDateChangeListener { view, year, month, dayOfMonth ->
val Date = (dayOfMonth.toString() + "-"
+ (month + 1 ) + "-" + year)
dateTV.setText(Date)
})
}
}
|
Now run your application to see the output of it.
Output:
Share your thoughts in the comments
Please Login to comment...