Created
May 31, 2022 12:08
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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