Introduction
- In the code below you will see how we can recreate the functionality of a Jetpack Compose
Checkbox
by using aBox
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
)
}
}
}
}
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.
Top comments (0)