abstract class TimePickerDialog2(
context: Context,
hourOfDay: Int, minute: Int, is24Hour: Boolean
) {
private val impl = DialogImpl(context, { view, hourOfDay, minute ->
if (onTimeSet(view, hourOfDay, minute)) {
dismiss()
}
}, hourOfDay, minute, is24Hour)
fun show() { impl.show() }
fun dismiss() { impl.dismiss() }
/** Called when user presses OK button. Return [true] to close dialog, [false] otherwise. */
abstract fun onTimeSet(view: TimePicker, hourOfDay: Int, minute: Int)
: Boolean
private class DialogImpl(
context: Context,
listener: OnTimeSetListener,
hourOfDay: Int, minute: Int, is24Hour: Boolean
) : TimePickerDialog(context, listener, hourOfDay, minute, is24Hour) {
var skipDismiss = false
override fun dismiss() { if (skipDismiss) { skipDismiss = false } else { super.dismiss() } }
override fun onClick(dialog: DialogInterface, which: Int) {
super.onClick(dialog, which)
skipDismiss = (which == BUTTON_POSITIVE)
}
}
}
Usage
object : TimePickerDialog2(this, 12, 15, false) {
override fun onTimeSet(view: TimePicker, hourOfDay: Int, minute: Int): Boolean {
if (/* the validations succeed */) {
return true
}
return false
}
}.show()
This implementation uses some hacky tricks to work around. Better to use custom AlertDialog
solution for this, as @ADM suggested above.