TimeInput
Common
Component in Material 3 Compose
Time pickers help users select and set a specific time.
Shows a time input that allows the user to enter the time via two text fields, one for minutes and one for hours Subscribe to updates through [TimePickerState]
Last updated:
Installation
dependencies {
implementation("androidx.compose.material3:material3:1.4.0-alpha01")
}
Overloads
@Composable
@ExperimentalMaterial3Api
fun TimeInput(
state: TimePickerState,
modifier: Modifier = Modifier,
colors: TimePickerColors = TimePickerDefaults.colors(),
)
Parameters
name | description |
---|---|
state | state for this timepicker, allows to subscribe to changes to [TimePickerState.hour] and [TimePickerState.minute], and set the initial time for this picker. |
modifier | the [Modifier] to be applied to this time input |
colors | colors [TimePickerColors] that will be used to resolve the colors used for this time input in different states. See [TimePickerDefaults.colors]. |
Code Example
TimeInputSample
@OptIn(ExperimentalMaterial3Api::class)
@Composable
@Preview
fun TimeInputSample() {
var showTimePicker by remember { mutableStateOf(false) }
val state = rememberTimePickerState()
val formatter = remember { SimpleDateFormat("hh:mm a", Locale.getDefault()) }
val snackState = remember { SnackbarHostState() }
val snackScope = rememberCoroutineScope()
Box(propagateMinConstraints = false) {
Button(modifier = Modifier.align(Alignment.Center), onClick = { showTimePicker = true }) {
Text("Set Time")
}
SnackbarHost(hostState = snackState)
}
if (showTimePicker) {
TimePickerDialog(
onCancel = { showTimePicker = false },
onConfirm = {
val cal = Calendar.getInstance()
cal.set(Calendar.HOUR_OF_DAY, state.hour)
cal.set(Calendar.MINUTE, state.minute)
cal.isLenient = false
snackScope.launch {
snackState.showSnackbar("Entered time: ${formatter.format(cal.time)}")
}
showTimePicker = false
},
) {
TimeInput(state = state)
}
}
}