Home > front end >  How to select only one item in a list (LazyColumn)?
How to select only one item in a list (LazyColumn)?

Time:06-10

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

CodePudding user response:

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
  • Related