Home > OS >  LazyColumn, Jetpack Compose. Single items() state by index
LazyColumn, Jetpack Compose. Single items() state by index

Time:09-16

I have a problem with the state of individual elements in LazyColumn and LazyRow. If the first element is open and I want to delete it, then the second element becomes the first and also becomes open. I want it to work differently.

Screen

enter image description here

Fragment LazyColumn

items(zamList.size) { index ->
                ExpandableCard()
            }

Expandable Card

@Composable
fun ExpandableCard() {

    //Expandable state
    var expandedState by remember {
        mutableStateOf(false)
    }

    Card(
        onClick = {
            expandedState = !expandedState
        }
    )

CodePudding user response:

You need to use unique keys with items. Using key will makes sure only the items that changed being recomposed and keeps order of items that are not changed based on their ids.

val myItems = listOf<MyItem>()

LazyColumn() {
    items(
        items = myItems,
        key = {item: MyItem ->  
            // Some unique id here
            item.hashCode()
        }
    ) {

    }
}

CodePudding user response:

It's a bad idea to combine LazyLists with remember:

Try adding 20 items, opening 1, and scrolling, until the item is not visible anymore: the item will have closed.

The way i suggest to do it is: Hold that state in a viewModel, e.g. a Map<YourItem, isOpen> onOpen/onClose update your viewmodel-state.


Other than that, it's a good idea to provide ids if possible.


Also, you might try Modifier.animateContentSize() (which is only defined in a LazyScope(!), so your animations look better :)

  • Related