android-jetpack-composeandroid-jetpackandroid-checkbox

how can we create a circular checkbox in jetpack compose?


It is usually possible to assign different shapes to a composable using a modifier, but this is not done in this composable.

I want the part marked in the image to be a circle

enter image description here

You can see the code I wrote below

@Composable
fun StandardCheckbox(
    text: String = "",
    checked: Boolean,
    onCheckedChange: ((Boolean) -> Unit)?,
) {
    Row(
        Modifier.padding(horizontal = SpaceMedium)
    ) {
        Checkbox(
            modifier = Modifier
                .clip(CircleShape),
            checked = checked,
            onCheckedChange = onCheckedChange,
            enabled = true,
            colors = CheckboxDefaults.colors(
                checkedColor = MaterialTheme.colors.primary,
                checkmarkColor = MaterialTheme.colors.onPrimary,
                uncheckedColor = MaterialTheme.colors.onBackground.copy(alpha = 0.3f)
            )
        )
        Spacer(modifier = Modifier.width(SpaceSmall))
        Text(
            text = text,
            color = MaterialTheme.colors.primary,
            modifier = Modifier.clickable {
                if (onCheckedChange != null) {
                    onCheckedChange(!checked)
                }
            }
        )
    }
}

Solution

  • The code below is from CheckboxImpl composable

    Canvas(modifier.wrapContentSize(Alignment.Center).requiredSize(CheckboxSize)) {
        val strokeWidthPx = floor(StrokeWidth.toPx())
        drawBox(
            boxColor = boxColor,
            borderColor = borderColor,
            radius = RadiusSize.toPx(),
            strokeWidth = strokeWidthPx
        )
        drawCheck(
            checkColor = checkColor,
            checkFraction = checkDrawFraction,
            crossCenterGravitation = checkCenterGravitationShiftFraction,
            strokeWidthPx = strokeWidthPx,
            drawingCache = checkCache
        )
    }
    

    drawBox will always draw a rounded rectangle. It can't be be customised.

    To implement the circular checkbox you need to write a custom Composable and draw Circle instead of Rectangle. You can use RadioButton and CheckboxImpl composable as reference.