Ask Your Question
2

What is the animation of the bottom sheet in Jetpack Compose?

asked 2022-08-16 11:00:00 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-05-28 14:00:00 +0000

huitzilopochtli gravatar image

In Jetpack Compose, the animation of the bottom sheet is achieved using the AnimatedVisibility and Modifier.offset functions.

First, we set up the bottom sheet layout with its initial state using a Scaffold composable:

Scaffold(
    bottomSheet = {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(200.dp)
        ) {
            // content of the bottom sheet
        }
    }
) {
    // rest of the screen content
}

To animate the visibility of the bottom sheet, we wrap the Box composable inside an AnimatedVisibility composable and set its visibility state:

var bottomSheetVisible by remember { mutableStateOf(false) }

Scaffold(
    bottomSheet = {
        AnimatedVisibility(
            visible = bottomSheetVisible,
            modifier = Modifier
                .fillMaxWidth()
                .height(200.dp)
        ) {
            Box(
                modifier = Modifier
                    .background(Color.White)
            ) {
                // content of the bottom sheet
            }
        }
    }
) {
    // rest of the screen content
}

Finally, to animate the position of the bottom sheet as it appears or disappears, we add a Modifier.offset to the Box composable and update its value based on the visibility state:

val sheetOffset = 200.dp

Scaffold(
    bottomSheet = {
        AnimatedVisibility(
            visible = bottomSheetVisible,
            modifier = Modifier
                .fillMaxWidth()
                .height(sheetOffset)
                .offset {
                    IntOffset(
                        x = 0,
                        y = if (bottomSheetVisible) 0 else sheetOffset.roundToPx()
                    )
                }
        ) {
            Box(
                modifier = Modifier
                    .background(Color.White)
            ) {
                // content of the bottom sheet
            }
        }
    }
) {
    // rest of the screen content
}

This will animate the bottom sheet in and out of the screen with a slide-up and slide-down motion.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-08-16 11:00:00 +0000

Seen: 16 times

Last updated: May 28 '21