Home > database >  how to Implement bottom sheet
how to Implement bottom sheet

Time:12-11

I want to Implement something smaller to that image when user click icon, button... it show to the user the opinions and cancel

overlay screen

CodePudding user response:

You can either use what's provided by Jetpack Compose, find more info here Jetpack Compose Scaffold Modal Bottom Sheet

Or you can make you own, here's an example implementation

@Composable
fun MyCustomBottomSheetScaffold(
    content: @Composable () -> Unit,
    isBottomSheetVisible: Boolean,
    onDismissRequest: () -> Unit,
    bottom: @Composable () -> Unit,
    overlayColor: Color = Color(0xAA_000000),
) {
    val actualOverlayColor = animateColorAsState(if (isBottomSheetVisible) overlayColor else Color.Transparent).value

    Box {
        content()

        Box(Modifier.fillMaxSize()
            .then(if (isBottomSheetVisible) Modifier.clickable { onDismissRequest() } else Modifier)
            .background(
                actualOverlayColor
            ),
            contentAlignment = Alignment.BottomCenter
        ) {
            AnimatedVisibility(
                isBottomSheetVisible,
                enter = slideInVertically(initialOffsetY = { it }),
                exit = slideOutVertically(targetOffsetY = { it }),
            ) {
                bottom()
            }
        }
    }
}

And here's how to use it

@Composable
fun BottomSheetExample() {
    // When this is true, the bottom sheet gets expanded
    var isBottomSheetVisible by remember { mutableStateOf(false) }
    MyCustomBottomSheetScaffold(
        content = {
            // Content goes here
            Box(Modifier.fillMaxSize().background(Color.Blue), contentAlignment = Alignment.Center) {
                Button(onClick = { isBottomSheetVisible = true }) {
                    Text("Open")
                }
            }
        },
        isBottomSheetVisible = isBottomSheetVisible,
        onDismissRequest = { isBottomSheetVisible = false },
        bottom = {
            // Bottom sheet content goes here
            Box(
                Modifier.fillMaxWidth()
                    .background(Color.White)
                    .clickable {
                        isBottomSheetVisible = false
                    }
                    .padding(16.dp),
                contentAlignment = Alignment.Center
            ) {
                Text("Close")

            }
        }
    )
}

CodePudding user response:

Just one clarification, if you decide to go with this answer (suggested by Benoit TH): Jetpack Compose Scaffold Modal Bottom Sheet

You will need to use ModalBottomSheetLayout to have a bottom sheet with gray background above it like you showed in the example image provided. If you use the regular BottomSheetScaffold the behaviour is different, being the bottom sheet displayed without background on above it.

  • Related