Home > Mobile >  How can i select only one grid in jetpack compose?
How can i select only one grid in jetpack compose?

Time:04-17

var iconSize by remember { mutableStateOf(50.dp)}
var boxBorder by remember { mutableStateOf(1.dp)}

LazyVerticalGrid(
            columns = GridCells.Fixed(3),
            content = {

                items(itemList){ item ->

                    var isSelected by remember { mutableStateOf(false)}

                    if(isSelected){
                        iconSize = 70.dp
                        boxBorder = 2.dp
                    }else{
                        iconSize = 50.dp
                        boxBorder = 1.dp
                    }

                    Box(modifier = Modifier
                        .border(boxBorder)
                        .clickable {isSelected = !isSelected}
                    ){
                        Icon(
                            modifier = Modifier
                            .size(iconSize),
                            imageVector = Icons.Default.Settings,
                            contentDescription = null)
                    }
                }
            }
        )

This is my view, i want to only select one of them. I don't want to multiple selection, i want to single selection.

enter image description here

How can i achieve this?

CodePudding user response:

All remember inside items will be reset when the view of a particular item disappears from the screen while scrolling. You need to move it to the container level, then its lifecycle will be bound to LazyVerticalGrid itself.

You can now store the selected item instead of a boolean value.

var selectedItem by remember { mutableStateOf<Item?>(null) }

LazyVerticalGrid(
    columns = GridCells.Fixed(3),
    content = {
        items(itemList){ item ->

            val isSelected = item == selectedItem

            Modifier.clickable { selectedItem = item }

If your itemList is modifiable, the most stable solution is to store the id of the selected item. If only item content can be changed and the order/number is stable, you can also use the index of the selected items.

  • Related