Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force orientation for some screens in Jetpack Compose?

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?

like image 755
rysv Avatar asked Sep 06 '25 19:09

rysv


1 Answers

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)
}
like image 156
Philip Dukhov Avatar answered Sep 08 '25 10:09

Philip Dukhov