Pick dates using the new material date picker Android
2 min readMay 2, 2020
First things first, start by creating an android studio project in Android Studio and add the material design dependency in the app level build.gradle file
implementation 'com.google.android.material:material:1.1.0'
Next, we drag a button from the designer tool onto the activity_main layout file to show the date picker when the button is clicked. We also add a text view to display the selected date.
Steps to Create the date picker when the button is clicked
- Create a MaterialDatePicker Builder and set the title
- Use the Builder object to create the date picker
- show date picker
buttonPickDate.setOnClickListener {
// Create the date picker builder and set the title
val builder = MaterialDatePicker.Builder.datePicker()
.also {
title = "Pick Date"
}
// create the date picker
val datePicker = builder.build()
// set listener when date is selected
datePicker.addOnPositiveButtonClickListener {
// Create calendar object and set the date to be that returned from selection
val calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
calendar.time = Date(it)
textView.text = "${calendar.get(Calendar.DAY_OF_MONTH)}- " +
"${calendar.get(Calendar.MONTH) + 1}-${calendar.get(Calendar.YEAR)}"
}
datePicker.show(supportFragmentManager, "MyTAG")
}
That is that. We are done.
MaterialDatePicker.Builder also has the dateRangePicker() method that allows the selection of a date range.
Here is the result