0

How to hide an item in a LazyColumn in Android Compose?

I had a LazyColumn with more than a hundred items from which to select one.

Looking for a solution found the following Link1 and Link2.

But I felt that it was to complex to apply to my code.

2
  • Can you provide some of the code ? You can call a filter {} function to the list to return only items meeting the filter criteria. Commented Dec 16, 2023 at 19:21
  • Thank you stoyan_vuchev. I posted the question to provide a solution my self as I don't know how to post an article or something similar. Commented Dec 16, 2023 at 19:36

1 Answer 1

1

I am using Jetpasck Compose so I don't use XML layouts.

I found a solution for the case that the hidden Items follow a pattern or RegEx. Maybe yo can create an Extension function to make a custom made function to hide non pattern items.

Within the LazyColumn Scope I added a filter to the List then in the selection code I do a lookup in the unfiltered List

This a partial code using this option:

LazyColumn(modifier = Modifier.fillMaxWidth(), state = listState) {
                if (notSetLabel != null) {
                    item {
                        LargeDropdownMenuItem(
                            text = notSetLabel,
                            selected = false,
                            enabled = false,
                            onClick = { },
                        )

                    }
                }
                //Adding the filter. I my case a contains function was good enough
                itemsIndexed(items.filter { x -> x.toString().contains(term, true)
                }) { index, item ->
                    val selectedItem = index == selectedIndex
                    drawItem(
                        item,
                        selectedItem,
                        true
                    ) {
                        //onItemSelected(index, item) --- Original code
                        //Change the selection to a lookup for original index in the unfiltered List
                        onItemSelected(items.indexOf(item), item)
                        expanded = false
                    }

                    if (index < items.lastIndex) {
                        Divider(modifier = Modifier.padding(horizontal = 8.dp))
                    }
                }

            }

That is it every thing stays the same.

1
  • There you have it! It's a good idea to have an extension function, so the UI doesn't get polluted. Also, it's a good idea to filter the list inside the ViewModel for a better performance. Commented Dec 16, 2023 at 20:30

Not the answer you're looking for? Browse other questions tagged or ask your own question.