https://kotlinlang.org logo
n

Nat Strangerweather

09/22/2020, 5:32 PM
Hi guys, another basic question, as I am still a beginner. I am trying to create custom radio buttons. I've looked at the code for RadioButtons but I can't see how to make sure that a button is deselected when another one is clicked. Here is my code:
Copy code
@Composable
fun BoxCards(color: Color, gradientColor: Color, text: String, size: Dp) {
    val (selected, onSelected) = remember { mutableStateOf(false) }
    val tlRadius = animate(if (selected) 48.dp else 20.dp)
    val radius = animate(if (selected) 0.dp else 20.dp)
    val boxModifier = Modifier
        .size(size)
        .weight(1f)
        .clip(
            shape = RoundedCornerShape(
                topLeft = tlRadius, topRight = radius,
                bottomLeft = radius, bottomRight = tlRadius
            )
        )
        .toggleable(value = selected, onValueChange = onSelected)
        .background(
            VerticalGradient(
                0.0f to color,
                0.5f to gradientColor,
                1.0f to color,
                startY = 0.0f,
                endY = with(DensityAmbient.current) { 150.dp.toPx() }
            )
        )
    Box(
        boxModifier,
        gravity = Center
    ) {
        Text(text = text, color = Color.White)
    }
}
I've used a tutorial by one of the Google team for the animation... Is there a simple way of converting my BoxCards into radio button behaviour?
s

Se7eN

09/22/2020, 5:52 PM
If I understood it right, you need to move the state up:
Copy code
val selectedIndex: Int by remember { mutableStateOf(-1) }

items.forEachIndexed { index, item ->
    val selected = index == selectedIndex
    BoxCard(
        selected,
        onSelected = { selectedIndex = index } 
        ...
    )
}
And for your `BoxCard`:
Copy code
@Composable
fun BoxCard(
    selected: Boolean,
    onSelected: () -> Unit,
    ...
) {
    ...
}
n

Nat Strangerweather

09/22/2020, 5:54 PM
Thanks, it's making sense now, will give it a go! 😊
👍 1