Is this the right/best way to enable immersive mod...
# compose-android
b
Is this the right/best way to enable immersive mode (hide the system bars) for a specific composable?
Copy code
@Composable
fun ImmersiveContent() {
    val view = LocalView.current
    
    DisposableEffect(Unit) {
        val window = (view.context as? Activity)?.window ?: return@DisposableEffect onDispose {}
        val insetsController = WindowCompat.getInsetsController(window, view)
        
        // Enable immersive mode
        insetsController.apply {
            hide(WindowInsetsCompat.Type.systemBars())
            systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
        }
        
        // Restore when composable leaves
        onDispose {
            insetsController.show(WindowInsetsCompat.Type.systemBars())
        }
    }
    
    // Your content here
}
i
Keep in mind that this approach won't work if you animate from one ImmersiveContent to another one (e.g., if you go from one screen to another with
AnimatedContent
/
NavDisplay
/ etc since the new screen will enter composition (its
DisposableEffect
starts) first, then the old screen will leave composition (calling its
onDispose
), which leaves you in a non-immersive state
You'd need to to have a hoisted state that both screens talk to that has a counter for how many things are requesting an immersive state which is what would talk to the insetsController
(then each individual screen would use a
DisposableEffect
to add a counter when it enters and decrement the counter when it is disposed)
but besides considering using
LocalActivity
instead of casting your context, the insets stuff looks fine
s
Maybe take inspiration from something like this https://github.com/HedvigInsurance/android/blob/develop/app%2Ffeature%2Ffeature-odyssey%2Fsrc%2Fmain%2Fkotlin%2Fcom%2Fhedvig%2Fandroid%2Ffeature%2Fodyssey%2Fstep%2Faudiorecording%2Fui%2FScreenOnFlag.kt so you won't have problems with going from an immersive screen to another screen which is also immersive
b
Thanks guys. My use case is a demo with only a single immersive screen, so I should be good. 👍