Android Time Picker Dialog With Java Time (Kotlin)

May 4, 2019

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