Search code examples
androidandroid-studioandroid-jetpack-compose

how to apply animateContentSize from center?


Actually the compose is animating from the center, but its content, which is a button, is moving from top left to center while animating the compose.

I want the button to animate from the center. I tried adding .animateContentSize to button, and the box as well, but still the button animates from top left to center.

Here's the code:

@Composable
fun TopScreen(
    isScaffold: MutableState<Boolean>,
){
    AnimatedVisibility(
        visible = !isScaffold.value,
        modifier = Modifier
            .fillMaxSize()
            .animateContentSize(
                animationSpec = tween(durationMillis = 500, easing = LinearEasing)
            )
    ){
        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(Color.LightGray),
            contentAlignment = Alignment.Center
        ){
            Button(
                onClick = {
                    isScaffold.value = true
                },
                modifier = Modifier

            ) {
                Text(text = "GO TO BOTTOM SCREEN")
            }
        }
    }
}

Solution

  • You don't need Modiifer.animateContentSize() with AnimatedVisibility composable it has scaleIn and scaleOut transitions. All of the transitions you can use are available in official document.

    https://developer.android.com/jetpack/compose/animation/composables-modifiers#enter-exit-transition

    Also you can use state-hoisting instead of passing and modifying State.

    @Composable
    fun TopScreen(
        isScaffold: Boolean,
        onChange: (Boolean) -> Unit
    ) {
        AnimatedVisibility(
            visible = !isScaffold,
            modifier = Modifier
                .fillMaxSize(),
            enter = scaleIn(tween(durationMillis = 500, easing = LinearEasing)),
            exit = scaleOut(tween(durationMillis = 500, easing = LinearEasing))
    
        ) {
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .background(Color.LightGray),
                contentAlignment = Alignment.Center
            ) {
                Button(
                    onClick = {
                        onChange(isScaffold.not())
                    },
                    modifier = Modifier
    
                ) {
                    Text(text = "GO TO BOTTOM SCREEN")
                }
            }
        }
    }