Access the DatePicker in MainActivity.kt file
First of all, we declare a variable datePicker to access the DatePicker widget from the XML layout.
val datePicker = findViewById<DatePicker>(R.id.date_Picker)
then, we declare another variable today to get the current get like this.
val today = Calendar.getInstance() datePicker.init(today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DAY_OF_MONTH)
To display the selected date from the calendar we will use
{ view, year, month, day -> val month = month + 1 val msg = "You Selected: $day/$month/$year" Toast.makeText(this@MainActivity, msg, Toast.LENGTH_SHORT).show() }
We are familiar with further activities in previous articles like accessing button and set OnClickListener etc.
Kotlin
package com.w3wiki.myfirstkotlinapp import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.* import java.util.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super .onCreate(savedInstanceState) setContentView(R.layout.activity_main) val datePicker = findViewById<DatePicker>(R.id.date_Picker) val today = Calendar.getInstance() datePicker.init(today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DAY_OF_MONTH) ) { view, year, month, day -> val month = month + 1 val msg = "You Selected: $day/$month/$year" Toast.makeText( this @MainActivity , msg, Toast.LENGTH_SHORT).show() } } } |
DatePicker in Kotlin
Android DatePicker is a user interface control which is used to select the date by day, month and year in our android application. DatePicker is used to ensure that the users will select a valid date.
In android DatePicker having two modes, first one to show the complete calendar and second one shows the dates in spinner view.
We can create a DatePicker control in two ways either manually in XML file or create it in Activity file programmatically.
First we create a new project by following the below steps:
- Click on File, then New => New Project.
- After that include the Kotlin support and click on next.
- Select the minimum SDK as per convenience and click next button.
- Then select the Empty activity => next => finish.
Contact Us