Skip to content

Instantly share code, notes, and snippets.

@zivkesten
Created May 31, 2022 12:08
Show Gist options
  • Save zivkesten/00d3a25444e6dceb0fd2cbff58e65785 to your computer and use it in GitHub Desktop.
Save zivkesten/00d3a25444e6dceb0fd2cbff58e65785 to your computer and use it in GitHub Desktop.
An extendion function to pull bottom sheet above your view with jetpack compose content
private fun Activity.showAsBottomSheet(content: @Composable () -> Unit) {
val view = this.findViewById(android.R.id.content) as ViewGroup
val bottomSheet = ComposeView(this).apply {
val composeView = this
setContent {
val coroutineScope = rememberCoroutineScope()
val modalBottomSheetState =
rememberModalBottomSheetState(ModalBottomSheetValue.Hidden)
val isSheetOpened = remember { mutableStateOf(false) }
ModalBottomSheetLayout(
sheetBackgroundColor = Color.Transparent,
sheetState = modalBottomSheetState,
sheetContent = { content() }
) {}
BackHandler {
coroutineScope.launch {
modalBottomSheetState.hide() // will trigger the LaunchedEffect
}
}
// Take action based on hidden state
LaunchedEffect(modalBottomSheetState.currentValue) {
when (modalBottomSheetState.currentValue) {
ModalBottomSheetValue.Hidden -> {
when {
!isSheetOpened.value -> {
isSheetOpened.value = true
modalBottomSheetState.show()
}
else -> view.removeView(composeView)
}
}
else -> {
Log.i(TAG, "Bottom sheet ${modalBottomSheetState.currentValue} state")
}
}
}
}
}
view.addView(bottomSheet)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment