Wed. Jan 15th, 2025

In Jetpack Compose, you can implement a time picker dialog using either the TimePickerDialog from the Android framework or by using Jetpack Compose’s TimePicker API (available in Material3 or as an experimental API).

Here are two ways to implement a time picker dialog in Jetpack Compose:


1. Using TimePickerDialog from the Android Framework

This approach is based on using the traditional TimePickerDialog from the Android SDK, and you can easily integrate it into Jetpack Compose.

Example: Time Picker Dialog Using TimePickerDialog

import android.app.TimePickerDialog
import android.os.Bundle
import android.widget.TimePicker
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import java.util.*

@Composable
fun TimePickerExample() {
    var selectedTime by remember { mutableStateOf("Select Time") }
    var showDialog by remember { mutableStateOf(false) }

    // TimePickerDialog opening
    val openTimePicker = {
        val calendar = Calendar.getInstance()
        val timePickerDialog = TimePickerDialog(
            LocalContext.current,
            { _: TimePicker, hourOfDay: Int, minute: Int ->
                selectedTime = String.format("%02d:%02d", hourOfDay, minute)
            },
            calendar.get(Calendar.HOUR_OF_DAY),
            calendar.get(Calendar.MINUTE),
            true
        )
        timePickerDialog.show()
    }

    Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Button(onClick = openTimePicker) {
            Text("Pick Time")
        }

        Spacer(modifier = Modifier.height(16.dp))

        Text(text = selectedTime, style = MaterialTheme.typography.bodyLarge)
    }
}

2. Using Material3 TimePicker (Jetpack Compose)

Jetpack Compose’s Material3 provides a TimePicker component which is currently in an experimental state. You will need to enable experimental APIs in your project and add the correct dependencies.

To enable experimental features, ensure you include the following dependency in your build.gradle file:

implementation "androidx.compose.material3:material3:<latest_version>"

Example: Time Picker Dialog Using Material3 Time Picker

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.material3.TimePicker
import androidx.compose.material3.Text
import java.util.*

@Composable
fun TimePickerMaterial3() {
    var selectedTime by remember { mutableStateOf("Select Time") }
    var showDialog by remember { mutableStateOf(false) }

    // Show Time Picker when button is clicked
    val openTimePicker = {
        showDialog = true
    }

    Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Button(onClick = openTimePicker) {
            Text("Pick Time")
        }

        Spacer(modifier = Modifier.height(16.dp))

        Text(text = selectedTime, style = MaterialTheme.typography.bodyLarge)

        // Show Time Picker dialog
        if (showDialog) {
            TimePickerDialog(onDismiss = { showDialog = false }) { hour, minute ->
                selectedTime = String.format("%02d:%02d", hour, minute)
                showDialog = false
            }
        }
    }
}

@Composable
fun TimePickerDialog(onDismiss: () -> Unit, onTimeSelected: (Int, Int) -> Unit) {
    var hour by remember { mutableStateOf(0) }
    var minute by remember { mutableStateOf(0) }

    // TimePicker content
    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text(text = "Pick Time") },
        text = {
            TimePicker(
                hour = hour,
                minute = minute,
                onTimeChanged = { newHour, newMinute ->
                    hour = newHour
                    minute = newMinute
                }
            )
        },
        confirmButton = {
            TextButton(onClick = { onTimeSelected(hour, minute) }) {
                Text("OK")
            }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) {
                Text("Cancel")
            }
        }
    )
}

Explanation:

  1. TimePickerDialog:
  • This is a custom AlertDialog that shows a TimePicker component.
  • It allows users to select an hour and minute, and it will update the time when the OK button is clicked.
  • The dialog can be dismissed with the cancel button.
  1. State Management:
  • hour and minute are managed using remember and mutableStateOf.
  • The time is formatted as hh:mm.

Key Features:

  1. Traditional TimePickerDialog:
  • A standard approach that works across all Android versions.
  • Simple to integrate and works well for basic use cases.
  1. Jetpack Compose Material3 TimePicker:
  • More modern and composable.
  • It gives you more control over the UI and behavior, such as how the time picker is displayed and styled.

These examples should cover most use cases for integrating a time picker in your Jetpack Compose application. You can customize the UI and behavior as per your requirements.

By Rajashekar

I’m (Rajashekar) a core Android developer with complimenting skills as a web developer from India. I cherish taking up complex problems and turning them into beautiful interfaces. My love for decrypting the logic and structure of coding keeps me pushing towards writing elegant and proficient code, whether it is Android, PHP, Flutter or any other platforms. You would find me involved in cuisines, reading, travelling during my leisure hours.

Leave a Reply

Your email address will not be published. Required fields are marked *