Tuesday, June 9, 2020

android kotlin - CalendarView set minDate maxdate

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.app.Activity
import android.os.Bundle
import android.widget.*
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)


        // get a calendar instance
        val calendar = Calendar.getInstance()


        // set calendar view min date programmatically
        // calendar view min date 2022 june 7
        calendar.set(
            2022, // year
            5, // month june, 0 based index
            7 // day of month
        )
        calendarView.minDate = calendar.timeInMillis
    }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    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">

    <!---
        The maximal date shown by this calendar view
        in mm/dd/yyyy format. max date 2022 june 21
     -->

    <CalendarView
        android:id="@+id/calendarView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:maxDate="6/21/2022"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>