androidkotlinandroid-jetpack-composecompose-recompositionjetpack-compose-animation

How to Reset the state of compose views animating


I am building an onboarding fragment that gives users tips for each screen. there are multiple pages of a few lines:

Page 1

Button: Next

Page 2

Button: Finish

I want each view on the page to fade in progressively down the screen.

Then with a new page i want the items to reset and all fade in again from the top down.

I have tried using AnimatedVisibility but the problem is that elements keep their state so the fade effect doesnt play on the second page. Possibly AnimatedVisibility isnt the right choice for what i want to do?

So this is the code for a line. I want to reset the state object on each recomposition.

Or if someone has a better suggetion on how to do it - then that would also be excellent.

@Composable
    private fun Line(line: ActionResources, modifier: Modifier) {
        val state = remember {
            MutableTransitionState(false).apply {
                // Start the animation immediately.
                targetState = true
            }
        }
        AnimatedVisibility(state,
            enter = fadeIn(animationSpec = tween(durationMillis = 1000)),
            exit = fadeOut(animationSpec = tween(durationMillis = 1000))
        ) {
            Row(
                modifier = modifier
                    .padding(16.dp)
            ) {
                val color = line.color?.let { colorResource(it) } ?: MaterialTheme.colors.onSurface
                line.icon?.also {
                    Icon(
                        painter = painterResource(it),
                        tint = color,
                        contentDescription = stringResource(id = R.string.menu_search),
                        modifier = Modifier.padding(end = 8.dp).size(24.dp)
                    )
                }
                line.label?.also {
                    Text(
                        modifier = Modifier,
                        style = MaterialTheme.typography.body1,
                        color = color,
                        text = it
                    )
                }
            }
        }
    }

Solution

  • I can't compile your code especially ActionResources, but based on this

    I want to reset the state object on each recomposition.

    I can only suggest supplying a key to your remember {...} using the the line parameter.

     val state = remember (line) {
            MutableTransitionState(false).apply {
                // Start the animation immediately.
                targetState = true
            }
      }
    

    I'm not sure if this would solve your problem, but if you want this state to be re-calculated assuming the line parameter will always be different on succeeding re-compositions, then using it as remember {...}'s key will guarantee a re-calculation.