Android Time Picker Dialog With Java Time (Kotlin)

July 24, 2018

JavaTimePickerDialog

class JavaTimePickerDialog : DialogFragment() {
    lateinit var localTime: LocalTime
    var onOk: ((time: LocalTime?) -> Unit)? = null
    var onCancel: (() -> Unit)? = null

    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
        }
    }

    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")
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.