MainActivity.kt
package com.cfsuman.kotlintutorials
import android.app.Activity
import android.os.Bundle
import android.widget.*
import java.text.DateFormat
import java.util.*
class MainActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// get the widgets reference from XML layout
val calendarView = findViewById<CalendarView>(R.id.calendarView)
val textView = findViewById<TextView>(R.id.textView)
// get a calendar instance
val calendar = Calendar.getInstance()
// set the calendar view date change listener
calendarView.setOnDateChangeListener {
view, year, month, dayOfMonth ->
// set the calendar date as calendar view selected date
calendar.set(year,month,dayOfMonth)
// format the calendar selected date
val dateFormatter = DateFormat
.getDateInstance(DateFormat.MEDIUM)
val formattedDate = dateFormatter.format(calendar.time)
// show calendar view selected date on text view
// medium format date
textView.text = formattedDate
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/rootLayout"
android:background="#DCDCDC"
android:padding="24dp">
<CalendarView
android:id="@+id/calendarView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:fontFamily="sans-serif"
android:textSize="24sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/calendarView"
tools:text="TextView" />
</androidx.constraintlayout.widget.ConstraintLayout>