DEV Community

Cover image for Quick and easy custom Jetpack compose checkbox
Tristan Elliott
Tristan Elliott

Posted on

1

Quick and easy custom Jetpack compose checkbox

Introduction

  • In the code below you will see how we can recreate the functionality of a Jetpack Compose Checkbox by using a Box with some animation.

UI Example

(Reddit embeds are not working on dev.to)

The code:

@Composable
fun CustomCheckBox(){
    var checked by remember { mutableStateOf(false) }
    val onPrimaryColor = if(checked) MaterialTheme.colorScheme.secondary else  MaterialTheme.colorScheme.onPrimary
    val primaryColor = MaterialTheme.colorScheme.primary
    val animatedColor by animateColorAsState(
        if (checked) MaterialTheme.colorScheme.secondary else primaryColor,
        label = "color"
    )

    Box(modifier = Modifier
        .border(1.dp, onPrimaryColor, RoundedCornerShape(5.dp))
        .height(20.dp)
        .width(20.dp)
        .drawBehind {
            val cornerRadius =
                5.dp.toPx() // must match the RoundedCornerShape(5.dp)
            drawRoundRect(
                color = animatedColor,
                cornerRadius = CornerRadius(cornerRadius, cornerRadius)
            )
        }
        .clip(
            RoundedCornerShape(5.dp)
        )
        .clickable {
            checked = !checked
        }
    ){
        Column( modifier = Modifier.align(Alignment.Center),) {
            AnimatedVisibility(
                checked,
                enter = scaleIn(initialScale = 0.5f), // Scale in animation
                exit = shrinkOut(shrinkTowards = Alignment.Center)
            ) {
                Icon(painter = painterResource(R.drawable.baseline_check_24),
                    contentDescription = "checked",
                    tint = MaterialTheme.colorScheme.primary
                )
            }
        }

    }
}

Enter fullscreen mode Exit fullscreen mode

Conclusion

  • Thank you for taking the time out of your day to read this blog post of mine. If you have any questions or concerns please comment below or reach out to me on Twitter.

Sentry mobile image

Improving mobile performance, from slow screens to app start time

Based on our experience working with thousands of mobile developer teams, we developed a mobile monitoring maturity curve.

Read more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more