androidandroid-jetpack-composeandroid-jetpack-compose-animation

AnimatedVisibility fadeIn animations do not work for recomposed items but only for items enter composition?


I'm filtering items based on user selection and animating them back in a FlowRow that also inside a LazyColumn with keys are unique, however Compose does not remove items from composition, which is also what i need for scroll to not jump, but items that are in composition from previous filter do not have fadeIn animations. Other animations like shrink/expand/slide work fine.

In gif at first filtering item1 and second filtering item3 does not animate fadeIn

enter image description here

This is the ViewModel and filtering, most code is omitted

class SomeViewModel : ViewModel() {

    private val list = listOf(
        SomeData(id = "1", value = "Row1"),
        SomeData(id = "2", value = "Row2"),
        SomeData(id = "3", value = "Row3"),
        SomeData(id = "4", value = "Row4"),
        SomeData(id = "5", value = "Row5")
    )

    var itemList by mutableStateOf(list)

    var filter: Int = 0

    fun filter() {
        if (filter % 3 == 0) {
            itemList = listOf(
                list[0],
                list[1],
                list[2]
            )
        } else if (filter % 3 == 1) {
            itemList = listOf(
                list[1],
                list[2]
            )
        } else {
            itemList = listOf(
                list[0],
                list[2],
                list[3]
            )
        }

        filter++
    }
}

data class SomeData(val id: String, val value: String)

Composable that contains items and animates after filtering takes effect.

@Composable
private fun StaggeredList(
    filter: String,
    itemList: List<SomeData>,
) {
    BoxWithConstraints(
        modifier = Modifier
    ) {

        val itemWidth = (maxWidth - 8.dp) / 2

        FlowRow(
            modifier = Modifier,
            maxItemsInEachRow = 2,
            horizontalArrangement = Arrangement.spacedBy(8.dp),
            verticalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            itemList.forEachIndexed { index, it ->
                key(it.id) {

                    var visible by remember {
                        mutableStateOf(false)
                    }

                    LaunchedEffect(filter) {
                        visible = false
                        delay(2000)
                        visible = true
                    }

                    AnimatedVisibility(
                        visible = visible,
                        enter = fadeIn(tween(2000)),
                        exit = fadeOut(tween(2000))
                    ) {
                        MyRow(
                            modifier = Modifier.size(itemWidth, 200.dp),
                            item = it
                        )
                    }
                }
            }
        }
    }
}

Rest of the code to reproduce the issue

@Preview
@Composable
private fun FlowRowCompositionPreview() {
    val viewModel = viewModel<SomeViewModel>()
    MyComposable(viewModel)
}

@Composable
fun MyComposable(someViewModel: SomeViewModel) {

    Column(modifier = Modifier.fillMaxSize().background(backgroundColor)) {

        val itemList = someViewModel.itemList

        LazyColumn(
            modifier = Modifier.fillMaxSize(),
            verticalArrangement = Arrangement.spacedBy(8.dp),
            contentPadding = PaddingValues(16.dp)
        ) {

            items(5) {
                Box(
                    modifier = Modifier
                        .background(Color.Red, RoundedCornerShape(16.dp))
                        .fillMaxWidth().height(100.dp)
                )
            }

            item {
                Button(
                    modifier = Modifier.padding(16.dp).fillMaxWidth(),
                    onClick = {
                        someViewModel.filter()
                    }
                ) {
                    Text("Filter")
                }
            }
            item {
                StaggeredList(
                    filter = someViewModel.filter.toString(),
                    itemList = itemList
                )
            }
        }
    }
}

Solution

  • Make enter and exit animations little shorter than delay in LaunchedEffect.

    When visibility changes before previous animation has ended, AnimatedVisibility stops the animation and content changes visibility instantly according to the new state. So when you set visible = true just before exit animation has ended, animation is stopped and items appear without enter animation.

    Edit:

    Correction - as @Thracian noted in comments, when interrupted, the other animation still plays, but very quickly. The speed of that animation is independent from the stage of the interrupted animation.

    enter image description here

    AnimatedVisibility uses Transition interanlly. In Transition.kt I found this piece of code:

    private fun updateAnimation(
        initialValue: T = value,
        isInterrupted: Boolean = false,
    ) {
        if (initialValueAnimation?.targetValue == targetValue) {
            // This animation didn't change the target value, so let the initial value animation
            // take care of it.
            animation = TargetBasedAnimation(
                interruptionSpec,
                typeConverter,
                initialValue,
                initialValue,
                velocityVector.newInstance() // 0 velocity
            )
            useOnlyInitialValue = true
            durationNanos = animation.durationNanos
            return
        }
        val specWithoutDelay =
            if (isInterrupted && !isSeeking) {
                // When interrupted, use the default spring, unless the spec is also a spring.
                if (animationSpec is SpringSpec<*>) animationSpec else interruptionSpec
            } else {
                animationSpec
            }
    

    Which implies that the interruption animation spec is interruptionSpec, which defined as:

    interruptionSpec = spring(visibilityThreshold = visibilityThreshold)