Home > Net >  How to select multiple items in LazyColumn in JetpackCompose
How to select multiple items in LazyColumn in JetpackCompose

Time:12-04

How to select multiple items in LazyColumn and finally add the selected items in a seperate list.

               GettingTags(tagsContent ={ productTags ->

                val flattenList = productTags.flatMap {
                    it.tags_list
                }
                Log.i(TAG,"Getting the flattenList $flattenList")

                LazyColumn{
                    items(flattenList){
                        ListItem(text = {Text(it) })
                        if(selectedTagItem) {
                            Icon(
                                imageVector = Icons.Default.Check,
                                contentDescription = "Selected",
                                tint = Color.Green,
                                modifier = Modifier.size(20.dp)
                            )
                        }
                    }
                }

            })

Mutable variable state

var selectedTagItem by remember{
    mutableStateOf(false)
}

CodePudding user response:

First create a class with selected variable to toggle

@Immutable
data class MyItem(val text: String, val isSelected: Boolean = false)

Then create a SnapshotStateList via mutableStateListOf that contains all of the items, and can trigger recomposition when we update any item with new instance, add or remove items also. I used a ViewModel but it's not mandatory. We can toggle items using index or get selected items by filtering isSelected flag

class MyViewModel : ViewModel() {

    val myItems = mutableStateListOf<MyItem>()
        .apply {
            repeat(15) {
                add(MyItem(text = "Item$it"))
            }
        }

    fun getSelectedItems() = myItems.filter { it.isSelected }

    fun toggleSelection(index: Int) {

        val item = myItems[index]
        val isSelected = item.isSelected

        if (isSelected) {
            myItems[index] = item.copy(isSelected = false)
        } else {
            myItems[index] = item.copy(isSelected = true)
        }
    }
}

Create LazyColumn with key, key makes sure that only updated items are recomposed, as can be seen in enter image description here

  • Related