With jetpack compose navigation, I suppose it may become a single activity app. How to force orientation only for certain composables (screens)? Say if I want to force landscape only when playing video and not other screens? Without navigation, can declare orientation in manifest but with navigation where we can specify this, possibly, at the composable level?
You can get current activity using LocalActivity
, and then update requestedOrientation
.
To set the desired orientation when the screen appears and bring it back when it disappears, use DisposableEffect
:
@Composable
fun LockScreenOrientation(orientation: Int) {
val activity = LocalActivity.current
DisposableEffect(orientation) {
val activity = activity ?: return@DisposableEffect onDispose {}
val originalOrientation = activity.requestedOrientation
activity.requestedOrientation = orientation
onDispose {
// restore original orientation when view disappears
activity.requestedOrientation = originalOrientation
}
}
}
Usage:
@Composable
fun Screen() {
LockScreenOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With