I am using material Date
Time
picker for my Android app. But I want to combine the Date
and Time
picker in one dialog.
Here's the tested Kotlin code for combining the DatePickerDialog
and TimePickerDialog
together. It becomes simpler because of the support of the closures in Kotlin. The following function should be placed in your Fragment
or Activity
. The requireContext()
method is a member of Fragment
. If you are using Activity
, use applicationContext
instead.
private fun pickDateTime() {
val currentDateTime = Calendar.getInstance()
val startYear = currentDateTime.get(Calendar.YEAR)
val startMonth = currentDateTime.get(Calendar.MONTH)
val startDay = currentDateTime.get(Calendar.DAY_OF_MONTH)
val startHour = currentDateTime.get(Calendar.HOUR_OF_DAY)
val startMinute = currentDateTime.get(Calendar.MINUTE)
DatePickerDialog(requireContext(), DatePickerDialog.OnDateSetListener { _, year, month, day ->
TimePickerDialog(requireContext(), TimePickerDialog.OnTimeSetListener { _, hour, minute ->
val pickedDateTime = Calendar.getInstance()
pickedDateTime.set(year, month, day, hour, minute)
doSomethingWith(pickedDateTime)
}, startHour, startMinute, false).show()
}, startYear, startMonth, startDay).show()
}
Call the above function in onClickListener
of your button as following:
button.setOnClickListener { pickDateTime() }
That's it!
If you want to show clock in 12 hour or 24 hour format depending on user's settings, replace false
with DateFormat.is24HourFormat(requireContext())