Search code examples
androidlistandroid-jetpack-composeandroid-jetpacklazycolumn

How to select only one item in a list (LazyColumn)?


I have a list of address and I want that my user select only one address for the shipping


Solution

  • You just need to keep track the index of selection.

    @Composable
    fun SingleSelectionList() {
        var selectedIndex by remember {
            mutableStateOf(-1)
        }
        LazyColumn(
            Modifier
                .fillMaxSize()
                .selectableGroup() // Optional, for accessibility purpose
        ) {
            items(count = 10) { index ->
                Text(
                    text = "Item $index",
                    Modifier
                        .fillMaxWidth()
                        .selectable(
                            selected = selectedIndex == index,
                            onClick = {
                                selectedIndex = index
                            }
                        )
                        .background(
                            if (selectedIndex == index) Color.Gray
                            else Color.Transparent
                        )
                        .padding(8.dp)
                )
            }
        }
    }
    

    if you want to allow deselection, you change the onClick to:

    selectedIndex = if (selectedIndex == index) -1 else index