Skip to content

Instantly share code, notes, and snippets.

@ElianFabian
Created September 10, 2025 08:54
Show Gist options
  • Save ElianFabian/d0fedad53bb657d73f3adf1c63c1b78c to your computer and use it in GitHub Desktop.
Save ElianFabian/d0fedad53bb657d73f3adf1c63c1b78c to your computer and use it in GitHub Desktop.
Simple time picker with custom minute interval.
package packageName
import android.app.AlertDialog
import android.content.Context
import android.view.Gravity
import android.widget.LinearLayout
import android.widget.NumberPicker
import java.time.LocalTime
import kotlin.math.roundToInt
@Suppress("FunctionName")
fun CustomTimePicker(
context: Context,
hour: Int? = null,
minute: Int ? = null,
interval: Int = 1,
onTimeSelected: (hour: Int, minute: Int) -> Unit = { _, _ -> },
onCancel: (() -> Unit)? = null,
): AlertDialog {
val dialogView = LinearLayout(context).apply {
orientation = LinearLayout.HORIZONTAL
setPadding(50, 20, 50, 20)
gravity = Gravity.CENTER
}
val now = LocalTime.now()
val initialHour = hour ?: now.hour
val rawMinute = minute ?: now.minute
val initialMinute = (rawMinute.toDouble() / interval).roundToInt()
val hourPicker = NumberPicker(context).apply {
minValue = 0
maxValue = 23
value = initialHour
}
val minutePicker = NumberPicker(context).apply {
minValue = 0
maxValue = (60 / interval) - 1
displayedValues = Array(60 / interval) { i -> String.format("%02d", i * interval) }
value = initialMinute
}
dialogView.addView(hourPicker)
dialogView.addView(minutePicker)
return AlertDialog.Builder(context)
.setView(dialogView)
.setPositiveButton(android.R.string.ok) { _, _ ->
val hour = hourPicker.value
val minute = minutePicker.value * interval
onTimeSelected(hour, minute)
}
.setNegativeButton(android.R.string.cancel) { _, _ ->
onCancel?.invoke()
}
.create()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment