animationandroid-jetpack-composeandroid-animationdata-classandroid-jetpack-compose-lazy-column

How Do You Animate The Insertion Of An Item Into A List In Android?


I've developed a simple android application where you can insert new items into a list on a button press. New items pop up instantly, it looks sloppy. I've tried to animate their insertion but it's not working.

The method of how I attempted to do this is by giving each item in the list a boolean that determines if the item is visible. On a button press, the boolean is set to true.

Here is the code:

This is the data class for each list item. It contains a boolean and string parameter.

data class Item(
    var isVisible: Boolean = false,
    val text: String
)

Here is the UI. It consists of a list, a button, a lazy column. The button adds a new item to the list and sets the isVisible parameter to true. The list is displayed in the lazy column.

Button(
    onClick = {
         items.add(
             Item(isVisible = true, text = "Item ${items.size + 1}")
         )
    }
) {
    Text("Add item")
}

LazyColumn {
    items(items) { item ->
        AnimatedVisibility(visible = item.isVisible) {
            Text(text = item.text)
        }
    }
}
 

It's not working. The list items still pop in instantly.


Solution

  • Jetpack Compose introduced the animateItem Modifier, which will animate insertion, deletion and reordering of items.

    You can use it as follows:

    LazyColumn {
        items(
            items,
            key = { it }  // provide key for correct animations
        ) { item ->
            Text(
                modifier = Modifier.animateItem(),  // apply Modifier
                text = item.text
            )
        }
    }
    

    Note that you need to specify the key parameter of the items function to assign a unique identifier of each Item for correct animations. In the code above, we are just taking the whole data class as key. You would need to make sure that each data class has a unique text value then.

    You will need at least Jetpack Compose 1.7.0-beta06 to use animateItem, or specify the foundation dependency version as follows:

    implementation "androidx.compose.foundation:foundation:1.7.0-beta06"