Zadbaj o dobrą organizację dzięki kolekcji
Zapisuj i kategoryzuj treści zgodnie ze swoimi preferencjami.
Selektory czasu często pojawiają się w oknach. Możesz użyć stosunkowo ogólnej i minimalnej implementacji okna lub wdrożyć okno niestandardowe, które daje większą elastyczność.
Najprostszym sposobem utworzenia okna dialogowego dla selektora czasu jest utworzenie funkcji kompozycyjnej, która implementuje interfejs AlertDialog. Poniższy fragment kodu zawiera przykład stosunkowo prostego okna dialogowego, które korzysta z tego podejścia:
Zwróć uwagę na najważniejsze punkty w tym fragmencie kodu:
Funkcja kompozycyjna DialWithDialogExample opakowuje element TimePicker w oknie.
TimePickerDialog to niestandardowy komponent, który tworzy AlertDialog z tymi parametrami:
onDismiss: funkcja wywoływana, gdy użytkownik zamknie okno (za pomocą przycisku zamykania lub nawigacji wstecz).
onConfirm: funkcja wywoływana, gdy użytkownik kliknie przycisk „OK”.
content: funkcja kompozycyjna, która wyświetla selektor czasu w oknie.
AlertDialog obejmuje:
Przycisk zamykania z etykietą „Zamknij”.
Przycisk potwierdzenia z etykietą „OK”.
Treść selektora czasu przekazana jako parametr text.
Funkcja DialWithDialogExample inicjuje funkcję TimePickerState z bieżącym czasem i przekazuje ją do funkcji TimePicker i onConfirm.
Rysunek 1. Selektor czasu w oknie AlertDialog.
Przykład zaawansowany
Ten fragment kodu pokazuje zaawansowaną implementację konfigurowalnego okna wyboru czasu w Jetpack Compose.
@ComposablefunAdvancedTimePickerExample(onConfirm:(TimePickerState)->Unit,onDismiss:()->Unit,){valcurrentTime=Calendar.getInstance()valtimePickerState=rememberTimePickerState(initialHour=currentTime.get(Calendar.HOUR_OF_DAY),initialMinute=currentTime.get(Calendar.MINUTE),is24Hour=true,)/** Determines whether the time picker is dial or input */varshowDialbyremember{mutableStateOf(true)}/** The icon used for the icon button that switches from dial to input */valtoggleIcon=if(showDial){Icons.Filled.EditCalendar}else{Icons.Filled.AccessTime}AdvancedTimePickerDialog(onDismiss={onDismiss()},onConfirm={onConfirm(timePickerState)},toggle={IconButton(onClick={showDial=!showDial}){Icon(imageVector=toggleIcon,contentDescription="Time picker type toggle",)}},){if(showDial){TimePicker(state=timePickerState,)}else{TimeInput(state=timePickerState,)}}}@ComposablefunAdvancedTimePickerDialog(title:String="Select Time",onDismiss:()->Unit,onConfirm:()->Unit,toggle:@Composable()->Unit={},content:@Composable()->Unit,){Dialog(onDismissRequest=onDismiss,properties=DialogProperties(usePlatformDefaultWidth=false),){Surface(shape=MaterialTheme.shapes.extraLarge,tonalElevation=6.dp,modifier=Modifier.width(IntrinsicSize.Min).height(IntrinsicSize.Min).background(shape=MaterialTheme.shapes.extraLarge,color=MaterialTheme.colorScheme.surface),){Column(modifier=Modifier.padding(24.dp),horizontalAlignment=Alignment.CenterHorizontally){Text(modifier=Modifier.fillMaxWidth().padding(bottom=20.dp),text=title,style=MaterialTheme.typography.labelMedium)content()Row(modifier=Modifier.height(40.dp).fillMaxWidth()){toggle()Spacer(modifier=Modifier.weight(1f))TextButton(onClick=onDismiss){Text("Cancel")}TextButton(onClick=onConfirm){Text("OK")}}}}}}
Zwróć uwagę na najważniejsze punkty w tym fragmencie kodu:
Funkcja kompozycyjna AdvancedTimePickerExample tworzy konfigurowalne okno wyboru czasu.
Używa komponentu Dialog, który zapewnia większą elastyczność niż AlertDialog.
Okno zawiera dostosowywany tytuł i przycisk przełączania między trybami wybierania i wpisywania.
Surface stosuje kształt i wysokość do okna, przy czym IntrinsicSize.Min dotyczy zarówno szerokości, jak i wysokości.
Układy Column i Row zawierają komponenty struktury okna.
W przykładzie śledzimy tryb selektora za pomocą parametru showDial.
Ikona IconButton umożliwia przełączanie się między trybami i odpowiednio zmienia swój wygląd.
Zawartość okna zmienia się między TimePicker a TimeInput w zależności od stanu showDial.
Ta zaawansowana implementacja zapewnia wysoce konfigurowalne i wielokrotnego użytku okno wyboru czasu, które można dostosować do różnych przypadków użycia w aplikacji.
Ta implementacja wygląda tak:
Rysunek 2. Selektor czasu w niestandardowym oknie.
Treść strony i umieszczone na niej fragmenty kodu podlegają licencjom opisanym w Licencji na treści. Java i OpenJDK są znakami towarowymi lub zastrzeżonymi znakami towarowymi należącymi do firmy Oracle lub jej podmiotów stowarzyszonych.
Ostatnia aktualizacja: 2025-08-27 UTC.
[[["Łatwo zrozumieć","easyToUnderstand","thumb-up"],["Rozwiązało to mój problem","solvedMyProblem","thumb-up"],["Inne","otherUp","thumb-up"]],[["Brak potrzebnych mi informacji","missingTheInformationINeed","thumb-down"],["Zbyt skomplikowane / zbyt wiele czynności do wykonania","tooComplicatedTooManySteps","thumb-down"],["Nieaktualne treści","outOfDate","thumb-down"],["Problem z tłumaczeniem","translationIssue","thumb-down"],["Problem z przykładami/kodem","samplesCodeIssue","thumb-down"],["Inne","otherDown","thumb-down"]],["Ostatnia aktualizacja: 2025-08-27 UTC."],[],[],null,["[Time pickers](/develop/ui/compose/components/time-pickers) often appear in dialogs. You can use a relatively generic and\nminimal implementation of a dialog, or you can implement a custom dialog with\nmore flexibility.\n\nFor more information on dialogs in general, including how to use the time picker\nstate, see the [Time pickers guide](/develop/ui/compose/components/time-pickers).\n\nBasic example\n\nThe most straightforward way to create a dialog for your time picker is to\ncreate a composable that implements [`AlertDialog`](/reference/kotlin/androidx/compose/material3/package-summary#AlertDialog(kotlin.Function0,kotlin.Function0,androidx.compose.ui.Modifier,kotlin.Function0,kotlin.Function0,kotlin.Function0,kotlin.Function0,androidx.compose.ui.graphics.Shape,androidx.compose.ui.graphics.Color,androidx.compose.ui.graphics.Color,androidx.compose.ui.graphics.Color,androidx.compose.ui.graphics.Color,androidx.compose.ui.unit.Dp,androidx.compose.ui.window.DialogProperties)). The following snippet\nprovides an example of a relatively minimal dialog using this approach:\n\n\n```kotlin\n@Composable\nfun DialWithDialogExample(\n onConfirm: (TimePickerState) -\u003e Unit,\n onDismiss: () -\u003e Unit,\n) {\n val currentTime = Calendar.getInstance()\n\n val timePickerState = rememberTimePickerState(\n initialHour = currentTime.get(Calendar.HOUR_OF_DAY),\n initialMinute = currentTime.get(Calendar.MINUTE),\n is24Hour = true,\n )\n\n TimePickerDialog(\n onDismiss = { onDismiss() },\n onConfirm = { onConfirm(timePickerState) }\n ) {\n TimePicker(\n state = timePickerState,\n )\n }\n}\n\n@Composable\nfun TimePickerDialog(\n onDismiss: () -\u003e Unit,\n onConfirm: () -\u003e Unit,\n content: @Composable () -\u003e Unit\n) {\n AlertDialog(\n onDismissRequest = onDismiss,\n dismissButton = {\n TextButton(onClick = { onDismiss() }) {\n Text(\"Dismiss\")\n }\n },\n confirmButton = {\n TextButton(onClick = { onConfirm() }) {\n Text(\"OK\")\n }\n },\n text = { content() }\n )\n}https://github.com/android/snippets/blob/5673ffc60b614daf028ee936227128eb8c4f9781/compose/snippets/src/main/java/com/example/compose/snippets/components/TimePickers.kt#L294-L337\n```\n\n\u003cbr /\u003e\n\nNote the key points in this snippet:\n\n1. The `DialWithDialogExample` composable wraps [`TimePicker`](/develop/ui/compose/components/time-pickers) in a dialog.\n2. `TimePickerDialog` is a custom composable that creates an `AlertDialog` with the following parameters:\n - `onDismiss`: A function called when the user dismisses the dialog (via the dismiss button or navigation back).\n - `onConfirm`: A function called when the user clicks the \"OK\" button.\n - `content`: A composable that displays the time picker within the dialog.\n3. The `AlertDialog` includes:\n - A dismiss button labeled \"Dismiss\".\n - A confirm button labeled \"OK\".\n - The time picker content passed as the `text` parameter.\n4. The `DialWithDialogExample` initializes the `TimePickerState` with the current time and passes it to both the `TimePicker` and the `onConfirm` function.\n\n**Figure 1.** A time picker in an AlertDialog.\n\nAdvanced example\n\nThis snippet demonstrates an advanced implementation of a customizable time\npicker dialog in Jetpack Compose.\n\n\n```kotlin\n@Composable\nfun AdvancedTimePickerExample(\n onConfirm: (TimePickerState) -\u003e Unit,\n onDismiss: () -\u003e Unit,\n) {\n\n val currentTime = Calendar.getInstance()\n\n val timePickerState = rememberTimePickerState(\n initialHour = currentTime.get(Calendar.HOUR_OF_DAY),\n initialMinute = currentTime.get(Calendar.MINUTE),\n is24Hour = true,\n )\n\n /** Determines whether the time picker is dial or input */\n var showDial by remember { mutableStateOf(true) }\n\n /** The icon used for the icon button that switches from dial to input */\n val toggleIcon = if (showDial) {\n Icons.Filled.EditCalendar\n } else {\n Icons.Filled.AccessTime\n }\n\n AdvancedTimePickerDialog(\n onDismiss = { onDismiss() },\n onConfirm = { onConfirm(timePickerState) },\n toggle = {\n IconButton(onClick = { showDial = !showDial }) {\n Icon(\n imageVector = toggleIcon,\n contentDescription = \"Time picker type toggle\",\n )\n }\n },\n ) {\n if (showDial) {\n TimePicker(\n state = timePickerState,\n )\n } else {\n TimeInput(\n state = timePickerState,\n )\n }\n }\n}\n\n@Composable\nfun AdvancedTimePickerDialog(\n title: String = \"Select Time\",\n onDismiss: () -\u003e Unit,\n onConfirm: () -\u003e Unit,\n toggle: @Composable () -\u003e Unit = {},\n content: @Composable () -\u003e Unit,\n) {\n Dialog(\n onDismissRequest = onDismiss,\n properties = DialogProperties(usePlatformDefaultWidth = false),\n ) {\n Surface(\n shape = MaterialTheme.shapes.extraLarge,\n tonalElevation = 6.dp,\n modifier =\n Modifier\n .width(IntrinsicSize.Min)\n .height(IntrinsicSize.Min)\n .background(\n shape = MaterialTheme.shapes.extraLarge,\n color = MaterialTheme.colorScheme.surface\n ),\n ) {\n Column(\n modifier = Modifier.padding(24.dp),\n horizontalAlignment = Alignment.CenterHorizontally\n ) {\n Text(\n modifier = Modifier\n .fillMaxWidth()\n .padding(bottom = 20.dp),\n text = title,\n style = MaterialTheme.typography.labelMedium\n )\n content()\n Row(\n modifier = Modifier\n .height(40.dp)\n .fillMaxWidth()\n ) {\n toggle()\n Spacer(modifier = Modifier.weight(1f))\n TextButton(onClick = onDismiss) { Text(\"Cancel\") }\n TextButton(onClick = onConfirm) { Text(\"OK\") }\n }\n }\n }\n }\n}https://github.com/android/snippets/blob/5673ffc60b614daf028ee936227128eb8c4f9781/compose/snippets/src/main/java/com/example/compose/snippets/components/TimePickers.kt#L342-L439\n```\n\n\u003cbr /\u003e\n\nNote the key points in this snippet:\n\n1. The `AdvancedTimePickerExample` composable creates a customizable time picker dialog.\n2. It uses a [`Dialog`](/reference/kotlin/androidx/compose/ui/window/package-summary#Dialog(kotlin.Function0,androidx.compose.ui.window.DialogProperties,kotlin.Function0)) composable for more flexibility than `AlertDialog`.\n3. The dialog includes a customizable title and a toggle button to switch between dial and input modes.\n4. `Surface` applies shape and elevation to the dialog, with `IntrinsicSize.Min` for both width and height.\n5. `Column` and `Row` layout provide the dialog's structure components.\n6. The example tracks the picker mode using `showDial`.\n - An `IconButton` toggles between modes, updating the icon accordingly.\n - The dialog content switches between `TimePicker` and `TimeInput` based on the `showDial` state.\n\nThis advanced implementation provides a highly customizable and reusable time\npicker dialog that can adapt to different use cases in your app.\n\nThis implementation appears as follows:\n**Figure 2.** A time picker in a custom dialog.\n\nAdditional resources\n\n- [Time pickers guide](/develop/ui/compose/components/time-pickers)\n- [Material Design - Time Pickers](https://m3.material.io/components/time-pickers/overview)"]]