Home > database >  How can I select only ONE element in a list (jetpack compose)?
How can I select only ONE element in a list (jetpack compose)?

Time:08-26

I have a list of Address and I want that my users select only ONE of them.

 LazyColumn {
            items(list.values.size) { index ->
                SelectAddress(
                    info = AddressList,
                    modifier = Modifier,
                    isSelectedAddress = false,
                    onSelectAddress = { /* TODO */ } )

In "SelectAddress" there are Text and checkbox like this:

@Composable
fun SelectAddress(
    isSelectedAddress: Boolean,
    onSelectAddress: (Boolean) -> Unit
) {
        val selectedAddress = remember { mutableStateOf(isSelectedAddress)}

Icon(
            painter = getCheckboxResource(isSelected = selectedAddress.value),
            contentDescription = "Checkbox",
            modifier = Modifier
                .clickable {
                    selectedAddress.value = selectedAddress.value.not()
                    onSelectAddress(selectedAddress.value)
                }
        )

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