Example of using CalendarView in an Android application
There Are Some Common Attributes for CalanderView :
id | This ID serves as the control's unique identity. |
layout_width | match_parent -> Text area contains fullscreen wrap_content-> Text area contains only text size |
layout_width | match_parent -> Text area contains fullscreen wrap_content-> Text area contains only text size |
Step 1:
File open res/layout/activity_main.xml file −
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<CalendarView
android:id="@+id/calendarView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Step 2:
File open com.microappvalley.newtestproject/MainActivity.kt file −
package com.microappvalley.newtestproject
import android.annotation.SuppressLint
import android.os.Bundle
import android.widget.CalendarView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
@SuppressLint("MissingInflatedId")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var calendarView:CalendarView=findViewById(R.id.calendarView)
calendarView.setOnDateChangeListener { view, year, month, dayOfMonth ->
// Display the selected date
val selectedDate = "Selected Date: " + (month + 1) + "/" + dayOfMonth + "/" + year
Toast.makeText(this@MainActivity,selectedDate,Toast.LENGTH_LONG).show()
}
}
}
Open Device Manager, run the emulator, and then run the application. Next, check the working output and check the output you declared in your code.