1

I am trying to LOCK the screen orientation for the entry screen of my application, and then reverse back to normal for the actual app and its features.

val systemUiController = rememberSystemUiController()
val context = LocalContext.current

I watched this tutorial, https://www.youtube.com/watch?v=U5G25kcaNu0 which uses this line:

this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTAIT)

But, this is controlled from the activity. I want to know, if it is possible to do this per screen view.

Alix Blaine
  • 585
  • 2
  • 16
  • what do you mean by "per screen view." ? a fragment, another function? – JustSightseeing Sep 06 '22 at 09:44
  • Hi, If I navigate via my navigation graph to a new Screen, that is a new composable that displays a different screen with content, I want to be able to via separate screen views, set the orientation lock. – Alix Blaine Sep 06 '22 at 09:47
  • If you were working with fragments it would be easier, but I believe there is still a way to do it, have you seen [this answer on a similar post](https://stackoverflow.com/a/69231996/15749574)? – JustSightseeing Sep 06 '22 at 09:53
  • I seen that post, but not attempted to try it. Seems way more complicated. – Alix Blaine Sep 06 '22 at 09:57

1 Answers1

5

You can access to Activity reference in Compose if you used setContent{} in Activity. This locks orientation to portrait mode.

val context = LocalContext.current

(context as? Activity)?.requestedOrientation = ActivityInfo. SCREEN_ORIENTATION_PORTAIT

When you wish to change back to sensor mode you can change to

@Composable
private fun OrientationSample() {
    Column(modifier = Modifier.fillMaxSize()) {
        val activity = (LocalContext.current as Activity)
        Button(onClick = {
            val orientation = activity.requestedOrientation
            val newOrientation = if (orientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
                ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
            } else {
                // This is where you lock to your preferred one
                ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
            }
            activity.requestedOrientation = newOrientation
        }) {
            Text("Toggle Orientation")
        }
    }
}
Thracian
  • 43,021
  • 16
  • 133
  • 222