Blog Infos
Author
Published
Topics
Published

In this article I’ll show you how to build a 24h time picker dialog using Jetpack Compose.

 

24 hour time picker dialog

 

@Composable
fun TimerPicker(
    onCancel: () -> Unit,
    onOk: (Time) -> Unit,
    modifier: Modifier = Modifier
)
data class Time(val hour: Int, val minute: Int)

At the beginning of the TimerPicker composable we need to define a few variables.

var selectedPart by remember { mutableStateOf(TimePart.Hour) }

var selectedHour by remember { mutableStateOf(0) }
var selectedMinute by remember { mutableStateOf(0) }
val selectedIndex by remember {
    derivedStateOf { if (selectedPart == TimePart.Hour) selectedHour else selectedMinute / 5 }
}

val onTime: (Int) -> Unit = remember {
    { if (selectedPart == TimePart.Hour) selectedHour = it else selectedMinute = it * 5 }
}
enum class TimePart { Hour, Minute }
@Composable
fun TimeCard(
    time: Int,
    isSelected: Boolean,
    onClick: () -> Unit
) {
    Card(
        shape = RoundedCornerShape(6.dp),
        backgroundColor = if (isSelected) selectedColor else secondaryColor,
        modifier = Modifier.clickable { onClick() }
    ) {
        Text(
            text = if (time == 0) "00" else time.toString(),
            fontSize = 32.sp,
            color = if (isSelected) secondaryColor else Color.White,
            modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp)
        )
    }
}

It’s just a card that displays the selected hour and minute. This is how they are placed in the TimerPicker component.

Row(
    modifier = Modifier.align(Alignment.CenterHorizontally)
) {
    TimeCard(
        time = selectedHour,
        isSelected = selectedPart == TimePart.Hour,
        onClick = { selectedPart = TimePart.Hour }
    )

    Text(
        text = ":",
        fontSize = 32.sp,
        color = Color.White,
        modifier = Modifier.padding(horizontal = 2.dp)
    )

    TimeCard(
        time = selectedMinute,
        isSelected = selectedPart == TimePart.Minute,
        onClick = { selectedPart = TimePart.Minute }
    )
}
@Composable
fun Clock(
    index: Int,
    modifier: Modifier = Modifier,
    content: @Composable () -> Unit
) {
    val localDensity = LocalDensity.current

    var radiusPx by remember { mutableStateOf(0) }
    val radiusInsidePx by remember { derivedStateOf { (radiusPx * 0.67).toInt() } }

    var indexCirclePx by remember { mutableStateOf(36f) }
    val padding by remember {
        derivedStateOf { with(localDensity) { (indexCirclePx * 0.5).toInt().toDp() } }
    }
...
}
fun posX(index: Int) =
    ((if (index < 12) radiusPx else radiusInsidePx) * cos(angleForIndex(index))).toInt()

fun posY(index: Int) =
    ((if (index < 12) radiusPx else radiusInsidePx) * sin(angleForIndex(index))).toInt()

If the index is smaller then 12, it means the time goes in the outer circle. If it’s bigger than or equal to 12, it goes in the inner circle.

private const val step = PI * 2 / 12
private fun angleForIndex(index: Int) = -PI / 2 + step * index

Now we finally come to the code that draws the clock, this is still inside the Clock composable.

Box(modifier = modifier) {
    Surface(
        color = primaryColor,
        shape = CircleShape,
        modifier = Modifier.fillMaxSize()
    ) {}

    Layout(
        content = content,
        modifier = Modifier
            .padding(padding)
            .drawBehind {
                val end = Offset(
                    x = size.width / 2 + posX(time),
                    y = size.height / 2 + posY(time)
                )

                drawCircle( // #1
                    radius = 9f,
                    color = selectedColor,
                )

                drawLine( // #2
                    start = center,
                    end = end,
                    color = selectedColor,
                    strokeWidth = 4f
                )

                drawCircle( // #3
                    radius = indexCirclePx,
                    center = end,
                    color = selectedColor,
                )
            }
    ) { measurables, constraints ->
        val placeables = measurables.map { it.measure(constraints) }
        assert(placeables.count() == 12 || placeables.count() == 24) { "Invalid items: should be 12 or 24, is ${placeables.count()}" }

        indexCirclePx = (constraints.maxWidth * 0.07).toFloat() // #4

        layout(constraints.maxWidth, constraints.maxHeight) {
            val size = constraints.maxWidth
            val maxElementSize = maxOf(placeables.maxOf { it.width }, placeables.maxOf { it.height })

            radiusPx = (constraints.maxWidth - maxElementSize) / 2 // #5

            placeables.forEachIndexed { index, placeable ->
                placeable.place( // #6
                    size / 2 - placeable.width / 2 + posX(index),
                    size / 2 - placeable.height / 2 + posY(index),
                )
            }
        }
    }
}

 

 

Job Offers

Job Offers


    Senior Android Developer

    SumUp
    Berlin
    • Full Time
    apply now

    Senior Android Engineer

    Carly Solutions GmbH
    Munich
    • Full Time
    apply now

OUR VIDEO RECOMMENDATION

, ,

Jetpack Compose Navigation: Beyond The Basics

One of the challenges facing Android engineers today is that while there is a myriad of information available surrounding the more established navigation with fragments, there are few practical resources on how to adapt to…
Watch Video

Jetpack Compose Navigation: Beyond The Basics

Miguel Kano
Android Engineer
Robinhood Markets, Inc

Jetpack Compose Navigation: Beyond The Basics

Miguel Kano
Android Engineer
Robinhood Markets, I ...

Jetpack Compose Navigation: Beyond The Basics

Miguel Kano
Android Engineer
Robinhood Markets, Inc

Jobs

Clock(
    time = selectedTime,
    modifier = Modifier
        .aspectRatio(1f)
        .align(Alignment.CenterHorizontally)
) {
    ClockMarks24h(selectedPart, selectedTime, onTime)
}

ClockMarks24h has the elements for a 24-hour clock.

@Composable
fun ClockMarks24h(selectedPart: TimePart, selectedTime: Int, onTime: (Int) -> Unit) {
    if (selectedPart == TimePart.Hour) {
        Mark(text = "00", index = 0, isSelected = selectedTime == 0, onIndex = onTime)
        (1..23).map {
            Mark(text = it.toString(), index = it, isSelected = selectedTime == it, onIndex = onTime)
        }
    } else {
        Mark(text = "00", index = 0, isSelected = selectedTime == 0, onIndex = onTime)
        Mark(text = "05", index = 1, isSelected = selectedTime == 1, onIndex = onTime)
        (2..11).map {
            Mark(text = (it * 5).toString(), index = it, isSelected = selectedTime == it, onIndex = onTime)
        }
    }
}

The Mark composable is what represents the hour and minute. It’s a normal component so it can be styled however you want.

@Composable
fun Mark(
    text: String,
    index: Int, // 0..23
    onIndex: (Int) -> Unit,
    isSelected: Boolean
) {
    Text(
        text = text,
        color = if (isSelected) secondaryColor else Color.White,
        modifier = Modifier.clickable(
            interactionSource = remember { MutableInteractionSource() },
            indication = null,
            onClick = { onIndex(index) }
        )
    )
}
@Composable
fun TimerPickerDialog() {
    val localContext = LocalContext.current

    Dialog(onDismissRequest = { /*TODO*/ }) {
        Box(modifier = Modifier.fillMaxWidth()) {
            TimerPicker(
                onOk = { Toast.makeText(localContext, it.toString(), Toast.LENGTH_SHORT).show() },
                onCancel = {},
                modifier = Modifier
                    .fillMaxWidth(0.8f)
                    .align(Alignment.Center)
            )
        }
    }
}

The final result:

YOU MAY BE INTERESTED IN

YOU MAY BE INTERESTED IN

blog
It’s one of the common UX across apps to provide swipe to dismiss so…
READ MORE
blog
In this part of our series on introducing Jetpack Compose into an existing project,…
READ MORE
blog
In the world of Jetpack Compose, where designing reusable and customizable UI components is…
READ MORE
blog

How to animate BottomSheet content using Jetpack Compose

Early this year I started a new pet project for listening to random radio…
READ MORE

Leave a Reply

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

Fill out this field
Fill out this field
Please enter a valid email address.

Menu