Amit Kairon
02/17/2025, 2:36 PMAmit Kairon
02/18/2025, 5:42 PM@Composable
actual fun ShowOverlay(key: Any?, content: @Composable () -> Unit) {
val context = LocalContext.current
val activity = context.getActivity()
if (activity == null) {
Napier.d(“Can’t show overlay, activity is null”)
return
}
val decor = activity.window.decorView as? ViewGroup
if (decor == null) {
Napier.d(“Can’t show overlay, decor is null”)
return
}
val layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
// We want the overlay to be always rendered above the entire content of the app.
// To do this we need to access the decor view of the activity and add our overlay to it.
DisposableEffect(key) {
val composeView = ComposeView(context).apply {
setContent { content() }
}
decor.addView(composeView, layoutParams)
onDispose {
decor.removeView(composeView)
}
}
}
private fun Context.getActivity(): Activity? = when (this) {
is Activity -> this
is ContextWrapper -> baseContext.getActivity()
else -> null
}
the following does show “content”
@Composable
actual fun ShowOverlay(key: Any?, content: @Composable () -> Unit) {
val window = UIApplication.sharedApplication.keyWindow
if (window == null) {
Napier.d(“Can’t show overlay, window is null”)
return
}
val screenSize = UIScreen.mainScreen.bounds.useContents { size.width to size.height }
// We create the overlay view to add to the window
val overlayView = UIView(CGRectMake(0.0, 0.0, screenSize.first, screenSize.second)).apply {
// backgroundColor = UIColor.blackColor.colorWithAlphaComponent(0.5) // Semi-transparent overlay
setFrame(CGRectMake(0.0, 0.0, 100.0, 100.0))
}
overlayView.backgroundColor = UIColor.blackColor.colorWithAlphaComponent(0.7) // Dim the background
val composeView = ComposeUIViewController { content() }
DisposableEffect(key) {
// Add the overlay and content view to the window
window.addSubview(overlayView)
overlayView.addSubview(composeView.view)
// Dispose logic to remove views when the composable is disposed
onDispose {
overlayView.removeFromSuperview()
composeView.view.removeFromSuperview()
}
}
}