Android Time Picker Dialog With Java Time (Kotlin)

JavaTimePickerDialog

class JavaTimePickerDialog : DialogFragment() {    companion object {        private const val TAG = "JavaTimePickerDialog"        private const val EXTRA_TIME = "time"        fun newInstance(time: LocalTime? = null): JavaTimePickerDialog {            val dialog = JavaTimePickerDialog()            val args = Bundle().apply {                putSerializable(EXTRA_TIME, time)                /*                time?.also {                    putLong(EXTRA_TIME, it.atStartOfDay(ZoneId.systemDefault()).toEpochSecond())                }                 */            }            dialog.arguments = args            return dialog        }    }    lateinit var localTime: LocalTime    var onOk: ((time: LocalTime?) -> Unit)? = null    var onCancel: (() -> Unit)? = null    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {        localTime = arguments?.getSerializable(EXTRA_TIME) as LocalTime? ?: run {            val now = LocalTime.now()            LocalTime.of(now.hour, now.minute)        }        val hour = localTime.hour        val minute = localTime.minute        val listener = TimePickerDialog.OnTimeSetListener { view, hourOfDay, minute ->            // if wanted to maintain seconds            // this.localTime = LocalTime.of(hourOfDay, minute, localTime!!.second)            // the following will zerorized second            this.localTime = LocalTime.of(hourOfDay, minute)            onOk?.invoke(localTime)        }        val dialog = TimePickerDialog(activity!!, listener, hour, minute, DateFormat.is24HourFormat(activity))        dialog.setOnCancelListener {            onCancel?.invoke()        }        return dialog    }}

Usage

val now = LocalDateTime.now()val dialog = JavaTimePickerDialog.newInstance(time=now.toLocalTime())dialog.onOk = { time ->    // do something}dialog.show(supportFragmentManager, "editTime")

Or you can create a convinient static method.

class JavaTimePickerDialog : DialogFragment() {    companion object {        ...        fun show(fragmentManager: FragmentManager, time: LocalTime?, listener: (time: LocalTime?) -> Unit): JavaTimePickerDialog {            val dialog = newInstance(time)            dialog.onOk = listener            dialog.show(fragmentManager, TAG)            return dialog        }    }    ...}

Usage

JavaTimePickerDialog.show(fragmentManager, null) { time ->    // do something}

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.