How to use Date Picker Dialog in Kotlin?
In this tutorial you will learn how to use Date Picker Dialog to pick Date and use it anywhere we want. We will show Date Picker Dialog on a Button click and save the picked date to a TextView.
Step 1: Create a new project OR Open your project
Step 2: Code
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
android:gravity="center"
tools:context=".MainActivity">
<Button
android:id="@+id/pickDateBtn"
android:text="Pick Date"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/dateTv"
android:text="Date"
android:textSize="30sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
MainActivity.kt
package com.jigopost.kotlinpractice
import android.app.DatePickerDialog
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import java.util.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val mPickTimeBtn = findViewById<Button>(R.id.pickDateBtn)
val textView = findViewById<TextView>(R.id.dateTv)
val c = Calendar.getInstance()
val year = c.get(Calendar.YEAR)
val month = c.get(Calendar.MONTH)
val day = c.get(Calendar.DAY_OF_MONTH)
mPickTimeBtn.setOnClickListener {
val dpd = DatePickerDialog(this, DatePickerDialog.OnDateSetListener { view, year, monthOfYear, dayOfMonth ->
// Display Selected date in TextView
textView.setText("" + dayOfMonth + " " + month + ", " + year)
}, year, month, day)
dpd.show()
}
}
}
Step 3: Output