Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lock orientation in Compose

Tags:

android

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.

like image 436
Alix Blaine Avatar asked Aug 25 '26 21:08

Alix Blaine


2 Answers

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")
        }
    }
}
like image 104
Thracian Avatar answered Aug 28 '26 11:08

Thracian


This solution actually locks the current orientation and then removes the lock when leaving the composition.

/**
 * Lock the current screen orientation while composed. Release the lock when the composition is left.
 */
@Composable
fun LockScreenOrientation() {
    val context = LocalContext.current
    DisposableEffect(context) {
        // Lock the screen orientation.
        context.requireActivity().requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LOCKED
        onDispose {
            // Release the the screen orientation lock.
            context.requireActivity().requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
        }
    }
}

/**
 * Find the activity context. If one isn't present, an exception is thrown.
 */
fun Context.requireActivity(): Activity {
    var context = this
    while (context is ContextWrapper) {
        if (context is Activity) return context
        context = context.baseContext
    }
    throw IllegalStateException("No activity was present but it is required.")
}
like image 27
Lucas Avatar answered Aug 28 '26 10:08

Lucas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!