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.
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")
}
}
}
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.")
}
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