I am using material Date
Time
picker for my Android app. But I want to combine the Date
and Time
picker in one dialog.
Based on @Yogesh Umesh Vaity's answer, I made an object for showing a DateTimePicker in Kotlin.
class DateTimePicker(val context: Context, var pickTime:Boolean = false, var calendar: Calendar = Calendar.getInstance(),
var callback: (it : DateTimePicker) -> Unit) {
companion object{
@JvmStatic
fun getFormat(format : String) : String{
when(format){
"d" -> return "dd/MM/yyyy"
"t" -> return "HH:mm"
"dt" -> return "dd/MM/yyyy HH:mm"
}
return "dd/MM/yyyy"
}
}
fun show(){
val startYear = calendar.get(Calendar.YEAR)
val startMonth = calendar.get(Calendar.MONTH)
val startDay = calendar.get(Calendar.DAY_OF_MONTH)
val startHour = calendar.get(Calendar.HOUR_OF_DAY)
val startMinute = calendar.get(Calendar.MINUTE)
DatePickerDialog(context, DatePickerDialog.OnDateSetListener { _, year, month, day ->
if(pickTime) {
TimePickerDialog(context, TimePickerDialog.OnTimeSetListener { _, hour, minute ->
calendar.set(year, month, day, hour, minute)
callback(this)
}, startHour, startMinute, true).show()
} else {
calendar.set(year,month,day)
callback(this)
}
}, startYear, startMonth, startDay).show()
}
fun showTime(){
val startYear = calendar.get(Calendar.YEAR)
val startMonth = calendar.get(Calendar.MONTH)
val startDay = calendar.get(Calendar.DAY_OF_MONTH)
val startHour = calendar.get(Calendar.HOUR_OF_DAY)
val startMinute = calendar.get(Calendar.MINUTE)
TimePickerDialog(context, TimePickerDialog.OnTimeSetListener { _, hour, minute ->
calendar.set(startYear, startMonth, startDay, hour, minute)
callback(this)
}, startHour, startMinute, true).show()
}
}
You could use the object from your Activity like this:
// Open Date Picker only and set an EditText
DateTimePicker(this){
val sdf = SimpleDateFormat(DateTimePicker.getFormat("d"), Locale.getDefault())
editText.setText(sdf.format(it.calendar.time))
}.show()
// Open Date Picker then Time picker and set an EditText
DateTimePicker(this, true){
val sdf = SimpleDateFormat(DateTimePicker.getFormat("dt"), Locale.getDefault())
editText.setText(sdf.format(it.calendar.time))
}.show()
// Open Time Picker only and set an EditText
DateTimePicker(this){
val sdf = SimpleDateFormat(DateTimePicker.getFormat("t"), Locale.getDefault())
editText.setText(sdf.format(it.calendar.time))
}.showTime()
// Use your own calendar object if you prefer to use your pre-configured calendar
val myCalendar = Calendar.getInstance()
myCalendar.set(Calendar.YEAR, 1995)
DateTimePicker(this, false, myCalendar){
val sdf = SimpleDateFormat(DateTimePicker.getFormat("d"), Locale.getDefault())
editText.setText(sdf.format(it.calendar.time))
}.show()